为什么通过 .Compile()Func<>
创建的Expression<Func<>>
a 比直接使用Func<>
声明的要慢得多?
我刚刚从使用Func<IInterface, object>
声明的直接更改为从Expression<Func<IInterface, object>>
我正在开发的应用程序中创建的声明,我注意到性能下降了。
我刚刚做了一个小测试,Func<>
从表达式创建的时间“几乎”是Func<>
直接声明的时间的两倍。
在我的机器上,DirectFunc<>
大约需要 7.5 秒,Expression<Func<>>
大约需要 12.6 秒。
这是我使用的测试代码(运行 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; }
}
我怎样才能恢复性能?
我能做些什么来让Func<>
创建的Expression<Func<>>
对象像直接声明的那样执行吗?