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

前端 未结 6 1739
囚心锁ツ
囚心锁ツ 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:14

    Just for the record: I can reproduce the numbers with the code above.

    One thing to note is that both delegates create a new instance of Foo for every iteration. This could be more important than how the delegates are created. Not only does that lead to a lot of heap allocations, but GC may also affect the numbers here.

    If I change the code to

    Func test1 = x => x * 2;
    

    and

    Expression> expression = x => x * 2;
    Func test2 = expression.Compile();
    

    The performance numbers are virtually identical (actually result2 is a little better than result1). This supports the theory that the expensive part is heap allocations and/or collections and not how the delegate is constructed.

    UPDATE

    Following the comment from Gabe, I tried changing Foo to be a struct. Unfortunately this yields more or less the same numbers as the original code, so perhaps heap allocation/garbage collection is not the cause after all.

    However, I also verified the numbers for delegates of the type Func and they are quite similar and much lower than the numbers for the original code.

    I'll keep digging and look forward to seeing more/updated answers.

提交回复
热议问题