Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoking nonstatic methods of a class

Tags:

c#

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.

like image 770
Rishi Bhatnagar Avatar asked Jul 30 '10 14:07

Rishi Bhatnagar


1 Answers

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.

like image 174
Elisha Avatar answered Sep 19 '22 05:09

Elisha