Why is code compiled with Expression <TDelegate> .Compile () slower than regular 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 than using reflection.
I also rewrote the same method in simple C # for comparison, and the code in C # is 4 times faster than the code compiled using Expression.Compile (). In my case, the method is called in a loop thousands of times.
Note that I extracted the first call from my profile to make sure that I do not measure compile time. So I compile the expression once, and then call it a thousand times.
Why is code compiled with Expression.Compile () slower than regular C #?
It has already been noted that you should cache and reuse the delegate, ideally ignoring the first run. To give a complete answer, we will need to see a concrete example. I really saw examples where it was faster (due to the fact that different IL flags were set).
So: it will depend on the code. I assume that your example does some kind of conversion or statement, which the C # compiler processes differently (optimized), but the expression should process in a general way (since it does not depend on the language).
Another factor is how things like literals and records are handled.