Static Vs Instance method performance differences

I think it is too late to post this info. Still I can see some question related to this topic in public newsgroups, hence this entry.

Here is my simple class.

      public class MyClass

      {

            public static void StaticHello()

            {

                  Console.WriteLine(”Hello”);

            }

            public void InstanceHello()

            {

                  Console.WriteLine(”Hello”);

            }

}

Here is a snippet from main method.

//Staic Method Invokation

MyClass.StaticHello();

 

      //Instance method invokation

      MyClass myClass = new MyClass();

      myClass.InstanceHello();

Both methods will do the same. Now question. What about the performance? Which one should I use? Well, all depends on what you want J

If you look the IL code for this app,

 .locals init ([0] class StaticMethodTest.MyClass myClass)

  IL_0000:  call       void StaticMethodTest.MyClass::StaticHello()

  IL_0005:  newobj     instance void StaticMethodTest.MyClass::.ctor()

  IL_000a:  stloc.0

  IL_000b:  ldloc.0

  IL_000c:  callvirt   instance void StaticMethodTest.MyClass::InstanceHello()

  IL_0011:  ret

ie static method is using calll and instance method is using callvirt instruction. Even if you edit your IL and replace  callvirt with call, application will work. But, callvirt will do null checking of the object, before it try to invoke methods. Obviously, static methods will be faster than instance method, since there is no null checking. Again, the difference is too small. 

No Comments

Leave a reply