I am a big fan of .NET reflection. However most often you will hear more of critics than praise. The biggest of all “It’s slow.” Web is full of cautions and warnings telling you not to use it. Some will go as far as saying that if you care for performance, do not even think about using reflection. If you go on and read beyond the highlight points, you will realize that a large percentage of these warnings and cautions are discussing a particular scenario where some developer failed to get what s/he was trying to achieve. And while being judgmental with the experiment a generalized statement like this comes up as an end result.
The problem of making such general rules about programming practices is that you tend to miss out the benefits by following these rules too literally in every context. Think it on the lines – Reflection or any feature for that matter, if included must have a valid reason for its presence. We should be able to see and know how and when to use it and when specifically to avoid it.
Reflection is slow; but the question is how slow is slow? One should worry about performance but this worry should not keep you away from making best use of a technology. If you look around in .NET world, you will realize that .NET framework itself uses a lot of reflection. Ability to store meta-data about your code and to be able to use it at runtime opens the door to a whole lot of possibilities limited only by your imagination.
If you rethink it it’s just one another way of storing and working with information; difference being that this information is stored in code itself. So instead of retrieving information from some XML file or database, you are pulling it in from the code itself. Therefore your concerns towards writing optimized code while reading data from XML (e.g., load once read many times) or from database (e.g., making fewer trips to database), etc. will not be much different when using reflection. You might want to fetch type info once and hold it for future calls as well instead of fetching it every time you need it.
As in case of database, we know where to use joins, on which columns to create indexes and which where clauses to use to get optimized execution time; in case of reflection too there is a well defined grammar to make optimized reflective calls. For example, using BindingFlags enumeration correctly, not trying to use IgnoreCase flag, and limiting your searches to public or static or instance members as required, will definitely give you best possible results. Joel Pobar’s post talks at length about how reflection works internally and is a good reference to understand how to avoid performance pitfalls.
Don’t just assume that reflection will hit the performance, but use it, test it, tweak it for performance optimization and enjoy the flexibility it provides. If you think your problem statement has a solution in reflection; don’t hesitate in going ahead just because someone says that it will be slow. If this turns out to be slow; there are ways to optimize it too. For instance Jon Skeet’s post talks about using Delegate.CreateDelegate to turn a MethodInfo into a strongly-typed delegate. This can improve performance massively in scenarios where you need to set the same properties multiple times. Essentially this means that a lot of the type checking is done once when you created the delegate, rather than on every invocation.
Let’s explore a scenario where reflection is no harm to use and probably the only way you can achieve the end result with.
You want dynamic extensibility to your desktop application; your revenue model includes selling various groups of features separately. You do not want to build multiple deployment packages and you want to be able to provide even more features to your customers after they have started using your application. How would you do it?
You might do this by developing a plug-in model in your application.
You may define an IMyAppPlugin interface which can be implemented in each of your application’s plug-in assembly implementing a specific feature. At minimum you may have following definition:
public interface IMyAppPlugin { Guid Identifier { get; } string Name { get; } string Copyright { get; } bool Start(IHostApp hostApp); void Stop(); bool Run(); }
You will not have any reference of these assemblies in your project at design time. Its only at runtime when you will try to discover these plug-in assemblies (using some mechanism such as looking in specific folder or registry, an XML file or anything else) and load it using reflection.
You will write code to find and create instance of the class that implements this IMyAppPlugin interface. Once you have this object you can initialize it by calling its Start() method passing your application’s reference as required. You may also write code to add access points (such as menu items) for this dynamic functionality to appear in your application’s user interface when this plug-in is successfully loaded.
A call to Run() method anytime after this will do what is desired.
So essentially what we are doing here is that we have loaded the assembly using reflection and we are calling methods dynamically again using reflection. If we just go by numbers, yes dynamically invoking a method is slow. Referring to Rick Strahl’s post we can say that invoking a method dynamically is about 3.5 to 4 times slower than directly calling of a method. But again the question needs to be asked – how slow is slow? Here we are talking about few milliseconds extra. Unless you are making calls in a loop for a large number of times, does it really matter in the larger perspective of a typical application? Most likely – No!
Remember .Net Framework and especially ASP.Net uses a lot of reflection internally to provide dynamic execution of code and controls.
Talking again about the above scenario, if not reflection, do we have some other relevant approach of dynamically extending the application? You may talk about using COM interfaces to achieve it – but reflection or no reflection – the essence of every approach is to dynamically resolve the address of the method to be called, which is the only major difference wrt static calls where this address is readily available.
This is just one scenario where reflection proves to be the most effective and simplified approach to work with. There are a lot of other scenarios where reflective access to properties, fields and methods provides enormous flexibility that simply wouldn’t be there otherwise.
With Dynamic Language Runtime (DLR) in .NET 4.0 we are heading towards a cleaner reflection. Eventually this may replace reflection how we see it today, due to its simplified code and caching advantages. In-fact as mentioned in this Jim hugunin’s post, it appears that DLR too internally makes good use of reflection.
In short, do not shy away from using reflection, just because you hear warnings about it. Always verify if these warnings apply to your project or scenario. Often they will not. As they say, “trust but verify!

By Ram Kripal Prasad on Oct 20, 2009
I agree! A word of caution though:
Reflection, like most other technologies, does not PROVIDE the benefits by mere itself. Its usage only ALLOWS certain advantages which can be best realized when accompanied by sound design.
Reply
By arjuns on Oct 26, 2009
Nice Read,
Reply