Why compiled lambda build over Expression.Call is slightly slower than delegate that should do the same?

江枫思渺然 提交于 2019-12-04 11:54:39

The compiled expression may be slower because of the reasons:

TL;DR;

The question is, why is the compiled delegate way slower than a manually-written delegate? Expression.Compile creates a DynamicMethod and associates it with an anonymous assembly to run it in a sand-boxed environment. This makes it safe for a dynamic method to be emitted and executed by partially trusted code but adds some run-time overhead.

There are tools like FastExpressionCompiler which help to mitigate the problem (disclaimer: I am an author)

Update: View IL of compiled delegate

  1. It is possible to get the compiled delegate IL as byte array:

    var hello = "Hello";
    Expression<Func<string>> getGreetingExpr = () => hello + " me";
    
    var getGreeting = getGreetingExpr.Compile();
    
    var methodBody = getGreeting.Method.GetMethodBody();
    
    var ilBytes = methodBody.GetILAsByteArray();
    
  2. You need a way to parse/read the array and convert it into IL instructions and parameters.

Pity, but I did not find the tooling or robust NuGet package to allow me to do so :-(

Here is the related SO question.

The closest tool may be this.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!