I am playing about the static reflection code from Joel Abrahamsson's blog and Daniel Cazzulino's blog. But I found their performance is kind of slow, even comparing with refection using "magic string".
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());
Here is the result:
- [Reflector] : 37823
- [Regular Reflection]: 780
- [Static Reflection]: 24362
So why should we prefer Static Reflection? Just remove "magic string"? Or we should add some caching to improve static reflection performance?