我正在尝试使用Joel Abrahamsson的博客和Daniel Cazzulino的博客关于静态反射代码的玩法。但是我发现它们的性能有点慢,即使与使用“魔术字符串”的反射相比。
int iterations = 1000000;
watch.Start();
for (int i = 0; i < iterations; i++)
{
var propertyOfName = Reflect<Employee>.GetProperty(c => c.Name);
}
watch.Stop();
Console.WriteLine("[Reflector]: " + watch.ElapsedMilliseconds.ToString());
watch.Reset();
watch.Start();
for (int i = 0; i < iterations; i++)
{
var propertyName = typeof (Employee).GetProperty("Name");
}
watch.Stop();
Console.WriteLine("[Regular Reflection]: " + watch.ElapsedMilliseconds.ToString());
watch.Reset();
watch.Start();
for (int i = 0; i < iterations; i++)
{
var propertyName = StaticReflection.GetMemberName<Employee>(c => c.Name);
}
watch.Stop();
Console.WriteLine("[StaticReflection]: " + watch.ElapsedMilliseconds.ToString());
以下是结果:
- [反射器]:37823
- [常规反射]:780
- [静态反射]:24362
那么为什么我们应该更喜欢静态反射呢?只是为了去除“魔法字符串”吗?还是我们应该添加一些缓存来提高静态反射的性能?