In C#, I'm marking some classes' properties with attributes and I'm using reflection to find these properties in order to perform gets and sets on them. I've found, however, that getting/setting with reflection in this manner is approximately 10x as slow as POCO gets/sets. Besides dropping the fundamental scenario described above to use alternate techniques, are there any documented tricks to make this significantly performant, such as caching techniques of some sort?
views:
246answers:
2Well, you could always store the PropertyInfo instance for the property once you get it and map it to whatever key works for you. Since the type is static, the PropertyInfo is not going to change, and storing a local reference is not going to kill you.
Assuming you don't do anything foolish to cache the value (like placing all the PropertyInfo instances in one long list and iterate the list every time to find it), you should be ok.
Of course, make sure you are not suffering from premature optimization disease before you go down this path. Identify that constantly calling GetProperty/GetProperties on your Type instance is a bottleneck in your application before making changes.
Going beyond what casperOne has said (including the bit about checking that this is the bottleneck), you may find it very helpful to convert the getters/setters into delegates (a Func<T>
and an Action<T>
for the getter and setter respectively) using Delegate.CreateDelegate. This can make a massive difference, and isn't terribly hard. If you're already going to cache the PropertyInfo, just cache the delegate pair instead.
I've got a blog post about Delegate.CreateDelegate - I first used it in anger when porting Protocol Buffers (which can be reflection-heavy at times). It helped a lot in that case.