Why would CreateDelegate be faster than a direct call ?

I'm stumped here.. can anyone explain why Delegate.CreateDelegate is faster than a direct call to a delegate?

(.NET 3.5.. 4.5.1, debug/release builds alike..)

see example code :

static void Main(string[] args) { var myDelegate = new Func<string, string>((s) => s); // Direct Call Stopwatch sw = new Stopwatch(); sw.Start(); for (int i = 0; i < 10000000; i++) { myDelegate("test"); } sw.Stop(); Console.WriteLine("DirectCall: \t\t{0}ms" ,sw.ElapsedMilliseconds); sw.Reset(); // CreateDeleagetCall var myDelegateCaller = (Func<string, string>)Delegate.CreateDelegate(typeof(Func<string, string>), myDelegate.Method); sw.Start(); for (int i = 0; i < 10000000; i++) { myDelegateCaller("test"); } sw.Stop(); Console.WriteLine("CreateDelegateCall: \t{0}ms", sw.ElapsedMilliseconds); Console.ReadLine(); } 

by lafeme via /r/csharp

Leave a Reply