What Is the "Cost" of .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 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).

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.

Performance cost of using `dynamic` vs `object`?

That would depend a lot on the exact scenario - but there is a layer of caching built in, so it is not as terrible as you might expect (it doesn't do reflection every time). It can also vary on the operations (for example, "lifted" nullable-T operations are noticeably slower). You would need to measure, but as it happens I have some timings here for member (property) access, that I took when doing FastMember:

Static C#: 14ms
Dynamic C#: 268ms
PropertyInfo: 8879ms (aka reflection)
PropertyDescriptor: 12847ms (aka data-binding)
TypeAccessor.Create: 73ms (aka FastMember)
ObjectAccessor.Create: 92ms (aka FastMember)

CAVEAT: these are for a single test that may not be representative of your scenario. This code is shown here

So: based on a simple test, about 20-times slower than static regular C#, but about 30 times faster than reflection.

UPDATE: interesting, looks like reflection got faster in .NET 4.5:

Static C#: 13ms
Dynamic C#: 249ms
PropertyInfo: 2991ms
PropertyDescriptor: 6761ms
TypeAccessor.Create: 77ms
ObjectAccessor.Create: 94ms

Here it is only about 12 times faster than reflection, because reflection got faster (not because dynamic got slower).

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();

Reflection performance and interface

On Slide 23 from Jeremy's "Practical Reflection in .NET" lecture (given in January, 2014), the following is presented:

  • Cast Types to a Known Interface
    All method calls go through the interface

    No dynamic method calls –no MethodInfo.Invoke

    Avoid interacting with private members

The basic idea is that it's better to use Reflection to find classes which implement a known interface then it is to find and directly use individual methods and properties. The reason?

  1. The fewer Reflection calls you have to make, the better. Each call to Reflection costs a lot of time (relatively speaking). It's much more effecient to make a single call to Reflection to get a class which implements a known Interface (from which point you can access members via the Interface) then it is to access each and every member via reflection.

  2. You can be reasonably confident that the class members associated with a known interface will behave in a particular way and not cause dangerous side effects. Arbitrarily grabbing methods and properties from a class based only on the name is extremely dangerous when dealing with third-party assemblies - you can't be reasonably certain that the method was meant to be used by you for your purpose.



Related Topics



Leave a reply



Submit