How Costly Is .Net Reflection

What is the cost of .NET reflection?

Reflection requires a large amount of the type metadata to be loaded and then processed. This can result in a larger memory overhead and slower execution. According to this article property modification is about 2.5x-3x slower and method invocation is 3.5x-4x slower.

Here is an excellent MSDN article outlining how to make reflection faster and where the overhead is. I highly recommend reading if you want to learn more.

There is also an element of complexity that reflection can add to the code that makes it substantially more confusing and hence difficult to work with. Some people, like Scott Hanselman believe that by using reflection you often make more problems than you solve. This is especially the case if your teams is mostly junior devs.

You may be better off looking into the DLR (Dynamic Language Runtime) if you need alot of dynamic behaviour. With the new changes coming in .NET 4.0 you may want to see if you can incorporate some of it into your solution. The added support for dynamic from VB and C# make using dynamic code very elegant and creating your own dynamic objects fairly straight forward.

Good luck.

EDIT: I did some more poking around Scott's site and found this podcast on reflection. I have not listened to it but it might be worth while.

How costly is .NET reflection?

It is. But that depends on what you're trying to do.

I use reflection to dynamically load assemblies (plugins) and its performance "penalty" is not a problem, since the operation is something I do during startup of the application.

However, if you're reflecting inside a series of nested loops with reflection calls on each, I'd say you should revisit your code :)

For "a couple of time" operations, reflection is perfectly acceptable and you won't notice any delay or problem with it. It's a very powerful mechanism and it is even used by .NET, so I don't see why you shouldn't give it a try.

Is using reflection in .Net effects the performance reasonably bad?

Yes, there is a cost involved in using Reflection.

However, the actual impact on the overall application performance varies. One rule of thumb is to never use Reflection in code that gets executed many times, such as loops. That will usually lead to algorithms that slow down exponentially (O(cn)).

In many cases you can write generic code using delegates instead of Reflection, as described in this blog post.

Reflection performance concerns

Firstly, chances are that this will not be the part of your application that is your bottleneck. For example, your use of the repository pattern suggests that you are talking to a database. This will be significantly slower than the code posted here. Profile your application and see what is slow and therefore worth spending time optimising.

Seocndly, to address your code, the only potential issue you should be aware of is that as you are returning an IEnumerable it could be evaluated multiple times which would cause the code to be run multiple times. To mitigate the added complexity this adds you should cache the result so that it will only get called once.

How slow is Reflection

In most cases: more than fast enough. For example, if you are using this to create a DAL wrapper object, the time taken to create the object via reflection will be minuscule compared to the time it needs to connect to a network. So optimising this would be a waste of time.

If you are using reflection in a tight loop, there are tricks to improve it:

  • generics (using a wrapper where T : new() and MakeGenericType)
  • Delegate.CreateDelegate (to a typed delegate; doesn't work for constructors)
  • Reflection.Emit - hardcore
  • Expression (like Delegate.CreateDelegate, but more flexible, and works for constructors)

But for your purposes, CreateInstance is perfectly fine. Stick with that, and keep things simple.


Edit: while the point about relative performance remains, and while the most important thing, "measure it", remains, I should clarify some of the above. Sometimes... it does matter. Measure first. However, if you find it is too slow, you might want to look at something like FastMember, which does all the Reflection.Emit code quietly in the background, to give you a nice easy API; for example:

var accessor = TypeAccessor.Create(type);
List<object> results = new List<object>();
foreach(var row in rows) {
object obj = accessor.CreateNew();
foreach(var col in cols) {
accessor[obj, col.Name] = col.Value;
}
results.Add(obj);
}

which is simple, but will be very fast. In the specific example I mention about a DAL wrapper—if you are doing this lots, consider something like dapper, which again does all the Reflection.Emit code in the background to give you the fastest possible but easy to use API:

int id = 12345;
var orders = connection.Query<Order>(
"select top 10 * from Orders where CustomerId = @id order by Id desc",
new { id }).ToList();

How is the performance of reflection APIs such as GetType() and GetTypes()?

We don't know what "good" and "bad" mean to you.

We don't know if you are using these in critical performance code that is likely to be a bottleneck to your application.

Only you know exactly the paths your code will take when using Object.GetType and Assembly.GetTypes.

Therefore, only you can profile exactly how meaningful the use of these methods will be on the performance of your application, and how beneficial it will be to try to boost the performance through caching.

I can tell you this: I have never had Type.GetType and Assembly.GetTypes be a bottleneck in my application, and I don't cache the results (I have, however, needed to cache MemberInfo.GetCustomAttributes but I only came to that conclusion after a profiler told me that it was a significant bottleneck in my application and that caching would substantially improve the performance).

Responding to your edit:

I mean, are these APIs take much time that might cause some performance degradation, or are these APIs well designed to ignore performance issues?

What alternatives do you have? If you need a reference to Type for a given object, or you need all the types in a given assembly, I assure you that Object.GetType and Assembly.GetTypes are your best choice. The question is, how are you using them? Again, we don't know, and therefore can't tell you what to do. You have to profile your real-world use of these functions and find out if they are causing a bottleneck in your application or not.

Is this use of attributes in .Net (C#) expensive?

"The usage of attributes" is too vague. Fetching the attributes is a reflection operation effectively - you wouldn't want to regularly do it in a loop - but they're not expensive to include in the metadata, and the typical usage pattern (IMO) is to build some other representation (e.g. an in-memory schema) after reading the attributes once.

There may well be some caching involved, but I'd probably cache the other representation anyway. For example, if I were decorating enum values with descriptions, I'd generally fetch the attributes once to build a string to enum dictionary (or vice versa).



Related Topics



Leave a reply



Submit