I'm curious how performant the Expression.Compile is versus lambda expression in the code and versus direct method usage, and also direct method calls vs virtual method calls (pseudo code):
var foo = new Foo();
var iFoo = (IFoo)foo;
foo.Bar();
iFoo.Bar();
(() => foo.Bar())();
(() => iFoo.Bar())();
Expression.Compile(foo, Foo.Bar)();
Expression.Compile(iFoo, IFoo.Bar)();
Expression.CompileToMethod(foo, Foo.Bar);
Expression.CompileToMethod(iFoo, IFoo.Bar);
MethodInfo.Invoke(foo, Foo.Bar);
MethodInfo.Invoke(iFoo, IFoo.Bar);
I didn't find any answer, so here is the performance test:
On my laptop (Release mode, 64 bit, .NET 4.5.2) it yields:
Hope this helps.
Hint: in release mode no call made at all in "Direct Call" case. CPU going from 00B531BC (mov eax ...) to 00B531C8 (jl 00B531BC) only.
We can split a question to 2 cases:
ExpressionTest.exe in Release mode with optimization (default release settings) .NET 4.5.2:
We see that "Direct Call" in 4.5 times faster than "Virtual Call". But as we see above it's no call at all. Bar method was inlined.
ExpressionTest.exe in Release mode with no optimization .NET 4.5.2:
So, "Direct Call" is about 3-4% faster than "Virtual Call".
Similar question: Performance of "direct" virtual call vs. interface call in C#