Why is a Func<>
created from an Expression<Func<>>
via .Compile() considerably slower than just using a Func<>
declared directly ?
I just changed from using a Func<IInterface, object>
declared directly to one created from an Expression<Func<IInterface, object>>
in an app i am working on and i noticed that the performance went down.
I have just done a little test, and the Func<>
created from an Expression takes "almost" double the time of an Func<>
declared directly.
On my machine the Direct Func<>
takes about 7.5 seconds and the Expression<Func<>>
takes about 12.6 seconds.
Here is the test code I used (running Net 4.0)
// Direct
Func<int, Foo> test1 = x => new Foo(x * 2);
int counter1 = 0;
Stopwatch s1 = new Stopwatch();
s1.Start();
for (int i = 0; i < 300000000; i++)
{
counter1 += test1(i).Value;
}
s1.Stop();
var result1 = s1.Elapsed;
// Expression . Compile()
Expression<Func<int, Foo>> expression = x => new Foo(x * 2);
Func<int, Foo> test2 = expression.Compile();
int counter2 = 0;
Stopwatch s2 = new Stopwatch();
s2.Start();
for (int i = 0; i < 300000000; i++)
{
counter2 += test2(i).Value;
}
s2.Stop();
var result2 = s2.Elapsed;
public class Foo
{
public Foo(int i)
{
Value = i;
}
public int Value { get; set; }
}
How can i get the performance back ?
Is there anything i can do to get the Func<>
created from the Expression<Func<>>
to perform like one declared directly ?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…