Best way to cache a reflection property getter / setter?

12,946

Solution 1

You should cache results of

typeof(T).GetProperty(propName); 

and

typeof(T).GetProperty(propName);

Another possible approach is to combine PropertyInfo.GetGetMethod Method (or PropertyInfo.GetSetMethod Method for setter) with Delegate.CreateDelegate Method and invoke the resulting delegate every time you need to get/set values. If you need this to work with generics you can use approach from this question: CreateDelegate with unknown types

This should be much faster compared to reflection: Making reflection fly and exploring delegates

There are also other ways to get/set values in a faster way. You can use expression trees or DynamicMethod to generate the il at runtime. Have a look at these links:

Late-Bound Invocations with DynamicMethod

Delegate.CreateDelegate vs DynamicMethod vs Expression

Solution 2

Well, the simplest answer is that you could cache the PropertyInfo object returned by GetProperty:

var propInfo = typeof(T).GetProperty(propName);
propInfo.SetValue(obj, value, null);
propInfo.GetValue(obj, null);

// etc.

That would eliminate the need for Reflection to repeatedly find the property in the class and eliminate the bulk of the performance hit.

Solution 3

Marc Gravell has written a brilliant article about his HyperDescriptor. It should provide a much faster runtime reflective property access.

Solution 4

Just store a reference to the PropertyInfo that is returned from:

typeof(T).GetProperty(propName)
Share:
12,946

Related videos on Youtube

michael
Author by

michael

Updated on June 04, 2022

Comments

  • michael
    michael almost 2 years

    I know that Reflection can be expensive. I have a class that gets/sets to properties often, and one way I figured was to cache the reflection somehow. I'm not sure if I'm supposed to cache an expression or what to do here really. This is what I'm currently doing:

    typeof(T).GetProperty(propName).SetValue(obj, value, null);
    typeof(T).GetProperty(propName).GetValue(obj, null);
    

    So... what would be the best way to make this quicker?

  • Dan Bryant
    Dan Bryant over 12 years
    +1, delegates are the way to go if you want the best performance
  • michael
    michael over 12 years
    The delegates seems like the way to go, but that article is a bit over my head. Could you show an example pertaining to what I'd be using it for?
  • Dave Cousineau
    Dave Cousineau about 8 years
    you say "you should cache results of X and Y", but X and Y are the same thing?