Skip to content

Instantly share code, notes, and snippets.

@RobertBouillon
Last active September 15, 2018 11:51
Show Gist options
  • Save RobertBouillon/ec73769e338b8ccbef8f4865c855cb15 to your computer and use it in GitHub Desktop.
Save RobertBouillon/ec73769e338b8ccbef8f4865c855cb15 to your computer and use it in GitHub Desktop.
.NET Delegate Invocation Performance Test
/*
RESULTS ON 7960X
CORE 2.1
Call 00:00:02.3531091
Invoke 00:00:02.3209331
Targeted 00:00:02.3206009
Targeted Invoke 00:00:02.3417757
FRAMEWORK 4.7.2
Call 00:00:02.3320065
Invoke 00:00:02.0597758
Targeted 00:00:02.0611660
Targeted Invoke 00:00:02.0611159
*/
using System;
using System.Diagnostics;
namespace Sandbox
{
class Program
{
static void Main(string[] args)
{
TestInvokePerformance();
}
private static void TestInvokePerformance()
{
const int iterations = 1_000_000_000;
Action a = NOP;
Func<int, int> b = NOP;
Func<int, int> c = (Func<int, int>)Delegate.CreateDelegate(typeof(Func<int, int>), b.Target, b.Method);
Time("Call", () =>
{
for (int i = 0; i < iterations; i++)
b(1);
});
Time("Invoke", () =>
{
for (int i = 0; i < iterations; i++)
b.Invoke(1);
});
Time("Targeted", () =>
{
for (int i = 0; i < iterations; i++)
c(1);
});
Time("Targeted Invoke", () =>
{
for (int i = 0; i < iterations; i++)
c.Invoke(1);
});
}
private static void Write(string test, TimeSpan elapsed) => Console.WriteLine($"{test,20} {elapsed}");
private static void Time(String test, Action action)
{
//Let's not time the JIT ;)
action();
Stopwatch sw = new Stopwatch();
sw.Start();
action();
sw.Stop();
Console.WriteLine($"{test,20} {sw.Elapsed}");
}
private static void NOP() => NOP(1); //Don't let the compiler optimize this call out because it's empty, so call another method.
private static int NOP(int a) => a;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment