In the process of optimizing reflection calls, I'm experimenting with using Delegate.CreateDelegate
and LambdaExpression.Compile
to turn my MethodInfo
s into faster delegates.
Based on this question, I expected LambdaExpression.Compile
to perform significantly better because it would generate actual MSIL for the method call -- somewhere close to a direct method invocation.
However, after benchmarking, I noticed that both techniques have roughly the same performance.
My hypothesis is that the overhead I'm getting when calling a delegate created using LambdaExpression.Compile
is due to the use of delegates itself. To confirm, I created another benchmark in which I manually created delegate directly invoking the method, and it had similar performance.
Therefore, my question is: is there any difference in the delegate object generated by LambdaExpression.Compile
and Delegate.CreateDelegate
?
I'm looking for a theoretical answer about the difference between the two approaches so I won't go into implementation details, but here is the jist of the implementation:
- For delegates: Making Reflection Fly and Exploring Delegates, by Jon Skeet
- For lambda expressions: using
Expression.Call
,Expression.Parameter
,Expression.Lambda
andExpression.Compile