Stupid Micro Benchmarking: Proxy Performance

time to read 2 min | 364 words

Let us take a look at this class:

public class Trivial
{
    public void EmptyStandard()
    {

    }

    public virtual void EmptyVirtual()
    {

    }

    [MethodImpl(MethodImplOptions.NoInlining)]
    public void EmptyNoInline()
    {

    }

    [MethodImpl(MethodImplOptions.NoInlining)]
    public virtual void EmptyVirtualNoInline()
    {

    }
}

Now let us see what is the effect of using Dynamic Proxy on performance, here is the test rig:

int count = 100000000;
var trivial = new Trivial();
Stopwatch sp = Stopwatch.StartNew();
for (int i = 0; i < count; i++)
    trivial.EmptyStandard();
Console.WriteLine("EmptyStandard: " + sp.ElapsedMilliseconds);
sp.Reset();
sp.Start();
for (int i = 0; i < count; i++)
    trivial.EmptyVirtual();
Console.WriteLine("EmptyVirtual: " + sp.ElapsedMilliseconds);
sp.Reset();
sp.Start();
for (int i = 0; i < count; i++)
    trivial.EmptyNoInline();
Console.WriteLine("EmptyNoInline: " + sp.ElapsedMilliseconds);
sp.Reset();
sp.Start();
for (int i = 0; i < count; i++)
    trivial.EmptyVirtualNoInline();
Console.WriteLine("EmptyVirtualNoInline: " + sp.ElapsedMilliseconds);


trivial = (Trivial)new ProxyGenerator().CreateClassProxy(typeof (Trivial));

sp.Reset();
sp.Start();
for (int i = 0; i < count; i++)
    trivial.EmptyVirtual();
Console.WriteLine("Proxy EmptyVirtual: " + sp.ElapsedMilliseconds);


sp.Reset();
sp.Start();
for (int i = 0; i < count; i++)
    trivial.EmptyVirtualNoInline();
Console.WriteLine("Proxy EmptyVirtualNoInline: " + sp.ElapsedMilliseconds);

The result of this is:

EmptyStandard: 382
EmptyVirtual: 397
EmptyNoInline: 557
EmptyVirtualNoInline: 520
Proxy EmptyVirtual: 6628
Proxy EmptyVirtualNoInline: 6372

On first glance, it is horrible, using a proxy have a 10x perf penalty. But notice just how many times I am running the code. a hundred million times, to be able to get anything observable.

As usual, this micro benchmark basically means that I don't really care about such things :-)