How much slower are delegate method calls than direct method calls? To test this, we use the Action type with a single parameter.
using System;
using System.Diagnostics;
class Program
{
const int _max = 100000000;
static void Main()
{
// Create Action delegate for Method1.
Action<int> action = new Action<int>(Method1);
var s1 = Stopwatch.StartNew();
// Version 1: use direct call.
for (int i = 0; i < _max; i++)
{
Method1(5);
}
s1.Stop();
var s2 = Stopwatch.StartNew();
// Version 2: use Action (delegate) call.
for (int i = 0; i < _max; i++)
{
action.Invoke(5);
}
s2.Stop();
Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000 * 1000) / _max).ToString(
"0.00 ns"));
Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000 * 1000) / _max).ToString(
"0.00 ns"));
}
static void Method1(int param)
{
// Dummy.
if (param == -1)
{
throw new Exception();
}
}
}
0.32 ns Direct call
3.52 ns Action Invoke call