Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cache Reflection Results (Class Properties)

considering that fairly static data should not be re-evaluated but cached instead, I wondered if it is possible to use Reflection to obtain class properties once, and then cache them so that I could dynamically evaluate object properties and read/assign values, but not have the Reflection overhead every time I do that. Is this possible (Sample code?) ?

To clarify a bit, lets say I have this class:

public class Cloud
{
     Boolean IsWhite;
}

and I'm trying to now make a method that allows me to do something like this (pseudocode):

Update(myCloudInstance, new {IsWhite, true});

Update should now check with the cache first if it knows already the properties of Cloud (typeof(myCloudInstance)), and then use cached information to assign the property "IsWhite" the value "true" instead of doing Reflection again.

Any ideas on how to do this?

like image 766
Alex Avatar asked Jul 30 '09 06:07

Alex


1 Answers

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.

like image 120
Jon Skeet Avatar answered Sep 28 '22 12:09

Jon Skeet