Why is Func<> created from Expression> slower than Func<> declared directly?

前端 未结 6 1748
囚心锁ツ
囚心锁ツ 2020-12-12 17:54

Why is a Func<> created from an Expression> via .Compile() considerably slower than just using a Func<>

6条回答
  •  星月不相逢
    2020-12-12 18:03

    I was interested in the answer by Michael B. so I added in each case extra call before stopwatch even started. In debug mode the compile (case 2) method was faster nearly two times (6 seconds to 10 seconds), and in release mode both versions both version was on par (the difference was about ~0.2 second).

    Now, what is striking to me, that with JIT put out of the equation I got the opposite results than Martin.

    Edit: Initially I missed the Foo, so the results above are for Foo with field, not a property, with original Foo the comparison is the same, only times are bigger -- 15 seconds for direct func, 12 seconds for compiled version. Again, in release mode the times are similar, now the difference is about ~0.5.

    However this indicates, that if your expression is more complex, even in release mode there will be real difference.

提交回复
热议问题