Why is code compiled with Expression<TDelegate>.Compile() slower than plain C#?
I rewrote a method that used reflection with new code that uses the System.Linq.Expressions classes and the Expression.Compile() method.
As expected, the program is much faster then us开发者_如何学Pythoning reflection.
I also rewrote the same method in plain C# to compare and the code in C# is 4 times faster than the code compiled with Expression.Compile(). In my case, the method is called in a loop, thousands of times.
Note that I have taken out the 1st call from my profiling to make sure I don't measure the time to compile. So I compile the expression once and then call it thousand of times.
Why is code compiled with Expression.Compile() slower than plain C#?
It had already been noted that you must cache and re-use the delegate, ideally ignoring the first run. To give a complete answer we would need to see a specific example. I've actually seen examples where it was faster (due to different IL flags being set).
So: it will depend on the code. My guess is that your example does some conversion or operator that the c# compiler handles differently (optimised), but Expression must handle in a generic way (since it is language independent).
Another factor is how things like literals and captures are handled.
精彩评论