title: C# generics performance vs interface
body: <p>Consider the following C# code:</p>
  <pre><code>interface IFace
  {
      void Do();
  }
  
  class Foo: IFace
  {
      public void Do() { /* some action */ }
  }
  
  class Bar
  {
      public void A(Foo foo) 
      {
          foo.Do();
      }
  
      public void B&lt;T&gt;(T foo)
          where T: IFace
      {
          foo.Do();
      }
  
      public void C(IFace foo)
      {
          foo.Do();
      }
  
      public void D&lt;T&gt;(T foo)
          where T: class, IFace
      {
          foo.Do();
      }
  }
  </code></pre>
  <p>with the following usage:</p>
  <pre><code>Foo foo = new Foo();
  Bar bar = new Bar();
  
  MeasureExecutionTime(() =&gt; bar.A(foo), &quot;A&quot;);
  MeasureExecutionTime(() =&gt; bar.B(foo), &quot;B&quot;);
  MeasureExecutionTime(() =&gt; bar.C(foo), &quot;C&quot;);
  MeasureExecutionTime(() =&gt; bar.D(foo), &quot;D&quot;);
  </code></pre>
  <p>The results (VS2015, .NET 4.5.2) are:</p>
  <blockquote>
  <p>A: 3,00 ns/op, 333,4 mop/s</p>
  <p>B: 5,74 ns/op, 174,3 mop/s</p>
  <p>C: 5,55 ns/op, 180,3 mop/s</p>
  <p>D: 5,64 ns/op, 177,4 mop/s</p>
  </blockquote>
  <p>I want to know why using the generic method <code>B</code> has completely no advantage over using interface in both x86 and x64 modes (like C++ templates vs virtual calls). The generic method is even slightly slower than non-generic interface-based method (this effect is steady and remains when B and C measurements are swapped).</p>
  <p>Appendix: MeasureExecutionTime code can be found here:
  <a href="https://gist.github.com/anonymous/9d60f5d09868ed3a00ec00f413f6afb0" rel="nofollow noreferrer">https://gist.github.com/anonymous/9d60f5d09868ed3a00ec00f413f6afb0</a></p>
  <p>Update: I have tested the code on Mono, the results are the following:</p>
  <blockquote>
  <p>andrew@ubuntu-nas:/data/mono/json/x64$ mono Test.exe</p>
  <p>A: 3.40 ns/op, 294.0 mop/s</p>
  <p>B: 3.40 ns/op, 293.7 mop/s</p>
  <p>C: 6.80 ns/op, 147.1 mop/s</p>
  <p>D: 3.40 ns/op, 294.2 mop/s</p>
  </blockquote>
  <p>The generated IL code can be found here:
  <a href="https://gist.github.com/anonymous/58df84eda906e83c64ce1b4fdc5497fb" rel="nofollow noreferrer">https://gist.github.com/anonymous/58df84eda906e83c64ce1b4fdc5497fb</a></p>
  <p>MS and Mono generates the same IL code except for the method <code>D</code>. Nevertheless, it cannot explain the difference for the method <code>B</code>. If I run MS-generated code by Mono without recompilation, the results for the method <code>D</code> become the same as for <code>B</code>.</p>