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?
Reflection is 104% slower than direct access (so about twice as slow). It also takes longer to warm up.
Reflection is slow for a few obvious reasons: The compiler can do no optimization whatsoever as it can have no real idea about what you are doing. This probably goes for the JIT as well. Everything being invoked/created has to be discovered (i.e. classes looked up by name, methods looked at for matches etc)
Reflection is not THAT slow. Invoking a method by reflection is about 3 times slower than the normal way. That is no problem if you do this just once or in non-critical situations. If you use it 10'000 times in a time-critical method, I would consider to change the implementation.
It is generally a bad idea to use reflection is application code, because you lose the strict type checking of the language. Reflection is generally for use by framework code, where it is essential. Good vs bad are not absolutes, but must be assessed in context.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With