83

Possible Duplicate:
How costly is .NET reflection?

I am currently in a programming mentality that reflection is my best friend. I use it a lot for dynamic loading of content that allows "loose implementation" rather than strict interfaces, as well as a lot of custom attributes.

What is the "real" cost to using reflection?

Is it worth the effort for frequently reflected types to have cached reflection, such as our own pre-LINQ DAL object code on all the properties to table definitions?

Would the caching memory footprint outwieght the reflection CPU usage?

Community
  • 1
  • 1
Tom Anderson
  • 10,807
  • 3
  • 46
  • 63
  • 21
    how in the world did i get a down vote on a topic that is 3 months old and answered? – Tom Anderson Jan 16 '09 at 20:33
  • We have automated our Data access layer using generic base classes and reflection. Most of our generic base classes are implemented using reflection. This has dramatically reduced the number of lines of code that we have to write for repetitive tasks. But there has been a performance hit. which solution did you adopt ? – this. __curious_geek Jun 30 '09 at 06:59
  • we went with a very similar approach and are are now caching the metadata. – Tom Anderson Jun 30 '09 at 07:23
  • 2
    Use the api at http://fasterflect.codeplex.com/. It will speed up reflection by like 500x for getters/setters/invokers and some other stuff. Source and info on how it works is there too if you need to extend it. – Brandon Moore Feb 10 '12 at 07:24
  • "Closed 7 years ago: _This question already has answers here:_" No answers provided. Is it April 1st? – ruffin Aug 25 '20 at 17:28

5 Answers5

61

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.

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
smaclell
  • 4,568
  • 7
  • 41
  • 49
  • The link to http://www.hanselman.com/ doesn't go to an article on reflection. – user1069816 Feb 01 '16 at 16:56
  • @user1069816, I did not find a particular article from Scott about the cost of reflection. He has mentioned it a few times on his Podcast in passing and went goes in depth into the topic in [Hanselminutes 27 - Reflection](http://www.hanselminutes.com/27/reflection). – smaclell Feb 01 '16 at 18:59
17

There are lots of things you can do to speed up reflection. For example, if you are doing lots of property-access, then HyperDescriptor might be useful.

If you are doing a lot of method-invoke, then you can cache methods to typed delegates using Delegate.CreateDelegate - this then does the type-checking etc only once (during CreateDelegate).

If you are doing a lot of object construction, then Delegate.CreateDelegate won't help (you can't use it on a constructor) - but (in 3.5) Expression can be used to do this, again compiling to a typed delegate.

So yes: reflection is slow, but you can optimize it without too much pain.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • 2
    It is amazing how many people do not know about Delegate.CreateDelegate, infact it has probably the best MSDN docs ever! – leppie Oct 22 '08 at 06:03
  • 2
    Link to MSDN for `CreateDelegate` http://msdn.microsoft.com/en-us/library/system.delegate.createdelegate.aspx – Dennis Mar 14 '12 at 16:28
2

With great power comes great responsibility.

As you say, reflection has costs associated with it, and depending on how much reflection you do it can slow the application down significantly.

One of the very approrpiate places to use it is for IoC (Inversion of Control) since, depending on the size of your application, would probably have more benefits than not.

Llyle
  • 5,980
  • 6
  • 39
  • 56
2

Thanks for the great links and great comments, especially on the part of the Jr Devs, that hit it right on the money.

For us it is easier for our junior developers to do this:

[TableName("Table")]
public class SomeDal : BaseDal
{
    [FieldName("Field")]
    public string Field
}

rather than some larger impelementations of DAL. This speeds up their building of the DAL objects, while hiding all the internal workings for the senior developers to gut out.

Too bad LINQ didn't come out earlier, I feel at times we wrote half of it.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Tom Anderson
  • 10,807
  • 3
  • 46
  • 63
  • Apparently NHibernate is quite good, according to the ALT.NET guys, so it might be worth taking a look at if you want an alternative. The last team I was a part of had a custom ORM layer that heavily used reflection. Only one person was ever able to understand it. – smaclell Oct 22 '08 at 02:44
  • Our final solution was to wrap this layer well enough so that if we have time later in the project it might be possible to remove the layer. Good luck and I feel your pain. – smaclell Oct 22 '08 at 02:46
0

One thing that can sometimes bite you when using reflection is not updating calls using reflection when doing refactoring. Tools like resharper will prompt you to update comments and strings when you change a method name, so you can catch most of them that way, but when you're calling methods that have been dynamically generated or the method name has been dynamically generated you might miss something.

The only solution is good documentation and thorough unit testing.

jonnii
  • 28,019
  • 8
  • 80
  • 108