What is the best way to create dynamic method on a fly but have it same efficient if it was compiled in VS?
Say I want create a calculator. User inputs formula say A + B / C * 0.5;
What I want is to be able to create something like Func which will accept A,B,C as double parameters and return double.
The parameters type and the return type are always double. Number of parameters are variable but at least one.
These formulas can be changed / added often. Once a formula ‘compiled’ it will be part of low latency code which can be called 1000 times / sec.
I need to find simple and reliable way to build it but it must have exact performance qualities of statically built and optimised method.
I have found Microsoft blog on this (Generating Dynamic Methods ) and compared performance between static method, compiled expression tree and IL injection.
Here is the code:
Here are 3 runs made on i7-920. Build – Release x64
Averages: 554 549 634
Static vs IL – IL 1% faster (!) no idea why though
Static vs ET – static 14% faster than expression tree
EDIT (Feb 2014) : I just ran the code above (with very slight modifications) on .NET 4.5 and faster CPU and got the new sets of results: Method / ET – 9%, Method / IL – 4%
Hence the previous results are not valid any more – the static method call is always faster..
*Not sure whether it is new hardware (i7-3820) or new .NET or perhaps I did something wrong in the old test.*
Another interesting result is that in 32-bit the very same code shows absolutely NO difference between the 3.