Reputation: 1822
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:
So why should we prefer Static Reflection? Just remove "magic string"? Or we should add some caching to improve static reflection performance?
Upvotes: 9
Views: 2384
Reputation: 28435
Have you seen http://ayende.com/blog/779/static-reflection ? He was using just delegates (not expression trees) and had improved compare to normal Reflection performance.
Example of the implementation
public static MethodInfo MethodInfo<TRet, A0>(Func<TRet, A0> func0)
{
return func0.Method;
}
Upvotes: 2
Reputation: 1062745
The main reason to "prefer" it would be static type checking by the compiler, to ensure you don't make a mess of it (and to ensure it works if you obfuscate, for example). However, IMO it is so rare that a typo here is a significant bug (meaning: I'm not including the brain-dead typo you spot and fix during development / unit-testing); so (since I am a performance nut) I typically advise to use the simplest option (string
). A particular example of this is when people are implementing the INotifyPropertyChanged
interface using tricks like this. Just pass a string
;p
Upvotes: 4