Compiled C# Lambda Expressions Performance

前端 未结 4 886
悲哀的现实
悲哀的现实 2020-12-04 05:44

Consider the following simple manipulation over a collection:

static List x = new List() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var result          


        
4条回答
  •  星月不相逢
    2020-12-04 06:26

    Compiled lambda performance over delegates may be slower because Compiled code at runtime may not be optimized however the code you wrote manually and that compiled via C# compiler is optimized.

    Second, multiple lambda expressions means multiple anonymous methods, and calling each of them takes little extra time over evaluating a straight method. For example, calling

    Console.WriteLine(x);
    

    and

    Action x => Console.WriteLine(x);
    x(); // this means two different calls..
    

    are different, and with second one little more overhead is required as from compiler's perspective, its actually two different calls. First calling x itself and then within that calling x's statement.

    So your combined Lambda will certainly have little slow performance over single lambda expression.

    And this is independent of what is executing inside, because you are still evaluating correct logic, but you are adding additional steps for compiler to perform.

    Even after expression tree is compiled, it will not have optimization, and it will still preserve its little complex structure, evaluating and calling it may have extra validation, null check etc which might be slowing down performance of compiled lambda expressions.

提交回复
热议问题