We’ve got into a very tricky scenario in a project. We have used lot of reflection in our project.
We have ..
- Validation Framework driven by Attributes and Reflection
- Extension methods that transaforms a DataRow to an Entity Object using Attributes and Reflection and vice versa. The same thing we have done for DataTable and EntityCollections.
- IComparer interface implemented on generic EntityComparer class that uses reflection to compare two Entity OBjects.
Like above scenarios we have used Reflections at many other parts in our appication. After using the reflection we have noticed that the application is taking more processing cycles with reflection.
Upto what extent we should use Reflection in our project ? What are the areas of a project that are most adversely affected by reflection in terms of processing ? Where reflection will not make any performance impact ? Are there any guidelines on using Reflection ?
Reflection is powerful, but has drawbacks. In general, try to code without it – but it is hugely useful for “framework” libraries, where you have little/limited knowledge what the actual objects will be; for example:
There are performance penalties with ad-hoc reflection, but if you are going to do it lots (within your library, and in a tight loop) you can mitigate against this:
Delegate.CreateDelegate(as a typed delegate; don’t useDynamicInvoke)Expressionin .NET 3.5And of course, any such code should be cached and re-used (you don’t want to compile+execute for every call; just the first – the rest should just execute).
Or there are libraries that abstract this; for example, HyperPropertyDescriptor wraps custom IL (for member access) in the familiar
PropertyDescriptorAPI – making it very fast but painless. Your question mentions data-tables and entities; which sounds a lot like this previous question, where I did some metrics using HyperDescriptor, with summary (in milliseconds):So my “take”: