Possible Duplicate:
What is the “cost” of reflection?
Does anyone have a good explanation of the generally accepted mantra that reflection == bad performance
?
For example, how expensive is it to iterate over a type's properties collection and extract all property values from an instance of this type compared to just accessing all the properties directly? One level of magnitude? Two? What does it depend on? Is it predictable at all? What is happening under the hood?
EDIT: Thanks for the answers so far. I've looked into some the links you provided and it seems that there is a vast gap of estimates out there regarding Reflection on Properties compared to direct access: from 2.5 times slower to 200 times slower.
This does not seem very reasonable to me. Some of you mentioned performance improvements in later versions of .Net so let be narrow my question to .Net 4.0. Does anyone have any benchmarks for that?
The best answer is that the generally accepted mantra is not as simple as it seems. reflection == bad performance
largely originated with .NET 1.0 and 1.1, and fails to acknowledge the performance improvements in later versions.
To be objective I've tested reflection-based solutions versus non-reflection based solutions on a number of occasions--and the winner isn't always one or the other. Reflection is what it is and it works how it works, it's not consistenly faster or slower and it (as with basically all programming approaches) can't be treated as a silver-bullet or as something to always be avoided.
There are several questions on SO that answer this in a variety of ways.
Here's a good one IMO: What is the "cost" of .NET reflection?
One of the articles the answerer links gives some interesting info on certain functions of reflection being more costly than others. For instance, doing a typeof isn't too bad, but invoking methods is more costly.
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