Skip to content

Instantly share code, notes, and snippets.

@mikeobrien
Created April 27, 2011 20:09
Show Gist options
  • Save mikeobrien/945070 to your computer and use it in GitHub Desktop.
Save mikeobrien/945070 to your computer and use it in GitHub Desktop.
class Program
{
static void Main()
{
const int iterations = 100;
const int repetitions = 100000;
long directDispatchStatic = 0, directDispatchInstance = 0, virtualDispatchBase = 0,
virtualDispatchOverride = 0, interfaceDispatch = 0;
var stopwatch = new Stopwatch();
for (var x = 1; x <= iterations; x++)
{
stopwatch.Restart();
for (var y = 0; y < repetitions; y++) Static.Add(1, 2);
stopwatch.Stop();
directDispatchStatic += stopwatch.ElapsedTicks;
var instance = new Instance();
stopwatch.Restart();
for (var y = 0; y < repetitions; y++) instance.Add(1, 2);
stopwatch.Stop();
directDispatchInstance += stopwatch.ElapsedTicks;
var virtualBase = new VirtualBase();
stopwatch.Restart();
for (var y = 0; y < repetitions; y++) virtualBase.Add(1, 2);
stopwatch.Stop();
virtualDispatchBase += stopwatch.ElapsedTicks;
var virtualOveride = new VirtualOverride();
stopwatch.Restart();
for (var y = 0; y < repetitions; y++) virtualOveride.Add(1, 2);
stopwatch.Stop();
virtualDispatchOverride += stopwatch.ElapsedTicks;
IInterface interfaceImplementation = new Interface();
stopwatch.Restart();
for (var y = 0; y < repetitions; y++) interfaceImplementation.Add(1, 2);
stopwatch.Stop();
interfaceDispatch += stopwatch.ElapsedTicks;
}
Console.WriteLine("-------------- Average ({0}*{1} Iterations) ---------------", iterations, repetitions);
Console.WriteLine("Direct dispatch (Static): {0} ticks", directDispatchStatic / iterations);
Console.WriteLine("Direct dispatch (Instance): {0} ticks", directDispatchInstance / iterations);
Console.WriteLine("Virtual dispatch (Base): {0} ticks", virtualDispatchBase / iterations);
Console.WriteLine("Virtual dispatch (Override): {0} ticks", virtualDispatchOverride / iterations);
Console.WriteLine("Interface dispatch: {0} ticks", interfaceDispatch / iterations);
Console.ReadKey();
}
}
public class Static
{ public static int Add(int a, int b) { return a + b; } }
public class Instance
{ public int Add(int a, int b) { return a + b; } }
public class VirtualBase
{ public virtual int Add(int a, int b) { return a + b; } }
public class VirtualOverride : VirtualBase
{ public override int Add(int a, int b) { return a + b; } }
public interface IInterface { int Add(int a, int b); }
public class Interface : IInterface
{ public int Add(int a, int b) { return a + b; } }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment