views:

565

answers:

4
+4  A: 

It's not clear exactly what you're doing, but caching can certainly make a difference with reflection.

In particular, if you're invoking methods (or property getters/setters) and can do so in a type-safe way as far as the calling code is concerned, it can make a huge difference if you convert the MethodInfo into a strongly-typed delegate once and then reuse that.

If you could give us a complete example of what you're trying to do, that would help us to come up with more specific ideas or even code. If you're just going to cache a PropertyInfo that may not have as much (or any) effect - it's possible that the normal Type.GetProperty (etc) methods are already pretty fast. As ever with performance questions, the key is to measure what you're actually doing. Make a change and measure again, etc.

Jon Skeet
Your answer hinted me in the right direction (how to cache PropertyInfo) which is actually faster than GetProperty (didnt time it yet, but responsiveness of my page appears improved.)
Alex
If you can cache delegates to call the property in a type-safe way, that may well make it faster again. Definitely time it though...
Jon Skeet
+1  A: 

The cost of reflection does not need to be as big as you think. In addition to delegates (that Jon discusses) you can also use things like HyperDescriptor to minimise the cost of reflection without changing the code much - it simply becomes PropertyDescriptor instead:

PropertyDescriptorCollection props = TypeDescriptor.GetProperties(myCloudInstance);
// ideally cache props, but not essential

then

object val = props["IsWhite"].GetValue(myCloudInstance);

or if you use it lots, consider storing the PropertyDescriptor somewhere, too.

However... like Jon, I'm really not 100% sure what you're trying to do!

Marc Gravell
A: 

Dynamic assembly should help with the concern about reflection performance. Somebody has implemented property assessors using dynamic assembly here.

Buu Nguyen
A: 

I think the best way to do it is to get the getter or setter method, convert it to a delegate, and work with the delegate, there is no faster way:

PropertyInfo propertyInfoProperty1 = type.GetType().GetProperty("Property1");
Func<TYPE, string> get_Property1 = (Func<TYPE, string>)Delegate.CreateDelegate(typeof(Func<TYPE, string>), propertyInfoProperty1.GetGetMethod());

Then call the getter method:

string value = get_Property1(type);

You can cache the delegates.

Ion Todirel