Why is a Func<>
created from an Expression
via .Compile() considerably slower than just using a Func<>
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.