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?
In C#, I’m marking some classes’ properties with attributes and I’m using reflection to
Share
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 anAction<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.