What (if any) is the upside or downside (performance, good coding practice, garbage collection etc.) of invoking a non-static method of a class in the manner below:
new ClassA().MethodA(param1, param2);
as against the more "traditional" way of
ClassA classA = new ClassA();
classA.MethodA(param1, param2);
Any thoughts would be greatly appreciated.
Coding
As for coding practice, the second option is better, where the object is stored in a variable first. The reason that makes it better is that you get to name the object according to the context where it's used. For example:
var pendingUserForRegistration = new User();
Performance
As for performance, the first option could be slightly better, since it uses the object directly from the stack and skips the storage of the object in a local variable. It can be seen from the IL of the methods:
IL of first:
.maxstack 8
L_0000: nop
L_0001: newobj instance void NS.ClassA::.ctor()
L_0006: call instance void MS.ClassA::M()
L_000b: nop
L_000c: ret
IL of second:
.maxstack 1
.locals init (
[0] class NS.ClassA c)
L_0000: nop
L_0001: newobj instance void NS.ClassA::.ctor()
L_0006: stloc.0
L_0007: ldloc.0
L_0008: callvirt instance void NS.ClassA::M()
L_000d: nop
L_000e: ret
This is usually a tiny performance overhead, it's hard to find a case where it'll solve a real performance problem.
Bottom line
Since the maintainability of the code gain here is greater than the performance gain it's preferred to store the object in a variable with meaningful name.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With