LambdaExpression Compile() vs CompileToMethod()

Jul 8, 2011 at 11:31 PM
Edited Jul 9, 2011 at 2:08 AM

I have a lot of formulas that are converted to lambda expression objects which then are compiled via the Compile method to executable code.

The problem that I am having is that the Compile method is too slow for my computing needs so I started to try other ways to compile the code, one of them being to use CompileToMethod.

I noticed that the Compile method is roughly 3-4 times slower than CompileToMethod, but the catch is that the code generated by the CompileToMethod is very slow compared to the code compiled with the Compile method. To give you an idea, the code that was compiled with Compile runs in 0.009s while the other code runs in 2.7s. Why there is such a difference ? I suspect that the Compile method generates optimized code while the other one doesn't.

Is there a way to control the compilation process with flags?

I am using .net 4.0.

Update: I just want to add the these discrepancies appear in debug mode. I run a test in Release mode and the numbers are leveled, the Compile method is almost as fast as the other method, and the code executed after using CompileToMethod is significantly faster but not as fast as the code produced by Compile.

Thank you