Access directly to a method in a class from its object

if the class has only one method that is not called at times, but rarely, then instead of calling the method in the traditional way, as shown below

RarelyCalledClass orarelyCalled = new RarelyCalledClass(); orarelyCalled.rarelyCalledMethod(); 

can i call it as below.

 (new RarelyCalledClass()).rarelyCalledMethod(); 

Will this increase performance since the compiler needs to do fewer operations.

+4
source share
3 answers

It will be exactly the same performance and code. You simply cannot access the instance anymore in your code. And readability is also worse (in my and most people).

You should also remember that you are always : Premature micro optimization is evil.

Application profile. Is this really a bottleneck? No? Then do not worry.

+3
source

Will this increase performance since the compiler needs to do less operation?

No. I do not think so.

I believe that you can check your IL code using any decompiler, you will see the same things.

The first code is IL,

  .locals init ([0] class _1.RarelyCalledClass orarelyCalled) IL_0000: nop IL_0001: newobj instance void _1.RarelyCalledClass::.ctor() IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: callvirt instance void _1.RarelyCalledClass::rarelyCalledMethod() IL_000d: nop IL_000e: ret 

Second IL code,

  .maxstack 8 IL_0000: nop IL_0001: newobj instance void _1.RarelyCalledClass::.ctor() IL_0006: call instance void _1.RarelyCalledClass::rarelyCalledMethod() IL_000b: nop IL_000c: ret 

Based on this structure,

 static void Main(string[] args) { // } } class RarelyCalledClass { public RarelyCalledClass() { } public void rarelyCalledMethod() { Console.WriteLine("Test"); } } 

The only difference is this: your first code uses stloc nad ldloc for stack problems, the second not.

+1
source

It should be the same after compilation, unless you use the instance somewhere later. However, ILSpy shows the difference:

First version (with purpose)

 .method private hidebysig static void Main ( string[] args ) cil managed { // Method begins at RVA 0x2058 // Code size 13 (0xd) .maxstack 1 .entrypoint .locals init ( [0] class ConsoleApplication1.TestClass obj ) IL_0000: newobj instance void ConsoleApplication1.TestClass::.ctor() IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: callvirt instance void ConsoleApplication1.TestClass::TestMethod() IL_000c: ret } // end of method Program::Main 

Second version (no assignment)

 .method private hidebysig static void Main ( string[] args ) cil managed { // Method begins at RVA 0x2058 // Code size 11 (0xb) .maxstack 8 .entrypoint IL_0000: newobj instance void ConsoleApplication1.TestClass::.ctor() IL_0005: call instance void ConsoleApplication1.TestClass::TestMethod() IL_000a: ret } // end of method Program::Main 

Both were created in Release mode.

0
source

All Articles