一直以来,我一直在阅读关于反射的文章,每个人都说:“反射很慢”,“反射很慢”。现在我决定测试一下它到底有多慢,让我惊讶的是,使用反射创建的委托实际上比使用 lambda 创建的委托快了约两倍。而且令人惊讶的是,使用声明方法创建的委托要慢大约四倍。
查看代码
这是一个自定义类,其属性获取方法将用于委托:
#class to test
class SomeClass
{
public SomeClass A { get; set; } //property to be gotten
public static SomeClass GetA(SomeClass c) { return c.A; } //declared getter method
}
这是我测试过的三个代表:
PropertyInfo AProp = typeof(SomeClass).GetProperty("A");
//1 - Created with reflection
Func<SomeClass, SomeClass> Getter = (Func<SomeClass, SomeClass>)Delegate.CreateDelegate(typeof(Func<SomeClass, SomeClass>), null, AProp.GetGetMethod());
//2 - Created with a lambda expression
Func<SomeClass, SomeClass> Getter2 = c => c.A;
//3 - Created from a declared method
Func<SomeClass, SomeClass> Getter3 = SomeClass.GetA;
这些是测试:
SomeClass C = new SomeClass();
C.A = new SomeClass(); //test doesn't change whether A is set or null
Stopwatch w;
//reflection delegate
w = Stopwatch.StartNew();
for (int i = 0; i < 10000000; i++) { SomeClass b = Getter(C); }
w.Stop(); Console.WriteLine(w.Elapsed);
//lambda delegate
w = Stopwatch.StartNew();
for (int i = 0; i < 10000000; i++) { SomeClass b = Getter2(C); }
w.Stop(); Console.WriteLine(w.Elapsed);
//method delegate
w = Stopwatch.StartNew();
for (int i = 0; i < 10000000; i++) { SomeClass b = Getter3(C); }
w.Stop(); Console.WriteLine(w.Elapsed);
//no delegate
w = Stopwatch.StartNew();
for (int i = 0; i < 10000000; i++) { SomeClass b = C.A; }
w.Stop(); Console.WriteLine(w.Elapsed);
结果如下:
我还尝试过倒转测试顺序,以查看是否有影响,或者手表是否在欺骗我,但是测试结果是一致的。
编辑:考虑到“发布”编译版本,如建议所示:
现在... 我本来期望 Lambda 要慢一些。