Probing a Hidden .NET Runtime Performance Enhancement

Jomo Fisher--Matt Warren once told me that the runtime had a performance optimization involving calling methods through an interface. If you only had a small number of implementations of a particular interface method the runtime could optimize the overhead of those calls. Coming from the C++ world where a vtable is a vtable this seemed a little odd to me. I finally got around to trying this out myself and he was right. Here's the code so you can try it for yourself:

 using System;
using System.Diagnostics;

class Program {
    static void Main(string[] args) {
        Stopwatch sw = new Stopwatch();
        DoManyTimes(new Call1());
        DoManyTimes(new Call2());
        DoManyTimes(new Call3());

    interface ICall {
        void Do();
    class Call1 : ICall { public void Do() { } }
    class Call2 : ICall { public void Do() { } }
    class Call3 : ICall { public void Do() { } }
    static void DoManyTimes(ICall ic) {
        for (int i = 0; i < 100000000; ++i)

On my machine this code reports values around ~2300 ms. Now, make a slight change and only use the Call1 class:

         DoManyTimes(new Call1());
        DoManyTimes(new Call1());
        DoManyTimes(new Call1());

Now I get numbers like ~1800 ms. Generally, I observed the following:

  • It doesn't seem to matter how many implementations of ICall there are. Its only whether there are many implementations of 'Do' called.
  • One implementation of 'Do'  performs better than two implementations. Two implementations performs better than three. After three, it doesn't seem to matter how many there are.
  • Delegate calls don't have an equivalent behavior.

 This posting is provided "AS IS" with no warranties, and confers no rights.