Tutorial :Performance Extension Method vs. Instance Method


Is there any performance difference between an instance method and an extension method?


Don't forget extension methods are just static method calls wrapped in syntactic sugar. So what you're really asking is

Is there a performance difference between static and instance methods

The answer is yes and there are various articles available on this subject

Some links


I would doubt there would be any performance difference because it is all syntactic sugar. The compiler just compiles it just as any other method call, except it is to a static method on a different class.

Some more details from my blog about the syntactic sugar: http://colinmackay.co.uk/2007/06/18/method-extensions/


It doesn't make any significant difference. See this article.

I've verified the results of the test, and did another test where the static variant had a parameter with type Sample. All of them took 11495ms (+/- 4ms) on my system for 2.1 billion calls. As the article says, you shouldn't be worrying about this.

Most examples and tests here aren't valid because they allow for method inlining. Especially easy on the compiler if the method is empty ;)

(interesting to see that the test was slower on my system than the one in the article.. it's not exactly slow, but it might be because of the 64bit OS)


There is a slight performance difference, due to the number of arguments being passed into the method. For instance, look at the following classes:

public class MyClassInstance  {      public int MyProperty { get; set; }        public MyClassInstance(int prop)      {          MyProperty = prop;      }        public void IncrementInstance()      {          MyProperty++;      }  }    public static class MyClassStatic  {      public static void IncrementStatic(this MyClassInstance i)      {          i.MyProperty++;      }  }  

running the following code:

        DateTime d = DateTime.Now;            MyClassInstance i = new MyClassInstance(0);            for (int x = 0; x < 10000000; x++)          {              i.IncrementInstance();          }            TimeSpan td = d - DateTime.Now;            DateTime e = DateTime.Now;            for (int x = 0; x < 10000000; x++)          {              i.IncrementStatic();          }            TimeSpan te = e - DateTime.Now;  

td = .2499 sec

te = .2655 sec

due to the fact that the instance method doesn't have to pass any arguments.

heres a slightly dated, but good article on performance

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »