测试类O:
class O
{
public int o;
}
行动1:
var in1 = new Action<O, int>((a, b) => a.o = b);
行动2:
var p1 = Expression.Parameter(typeof(O));
var p2 = Expression.Parameter(typeof(int));
var k = Expression.Assign(Expression.Field(p1, typeof(O).GetField("o")), p2);
var in2 = Expression.Lambda<Action<O, int>>(k, p1, p2).Compile();
测试方法:
void Test(int iteration, Action action)
{
var watch = new Stopwatch();
watch.Start();
for (var i = 0; i < iteration; i++) action();
watch.Stop();
// print
}
然后测试:
var o = new O();
Time(1000000000, () => in1(o, 8)) // 8273 ms
Time(1000000000, () => in2(o, 8)) // 6603 ms
那么为什么in2()比in1()更快?!?!?