views:

40

answers:

3

I have a method that has the following signature:

 private object GetNestedObject<y>(y objToAccess, string nestedObjectName)

I'm using Reflection to get the nestedObject from the objToAccess and return it.

This works well except it's really slow (I have to do this a few hundred thousand times). I came across HyperDescriptor, but since I'm running this on Linux, and Mono doesn't support TypeDescriptionProviders, I can't use it.

Are there any alternatives to using getValue in this case? I could always hardcode in overrides for each type, but that is not desirable and would add a lot of maintenance overhead in my case.

A: 

I'm not sure if Mono supports it, but for such cases (using Reflection in high-load code), I usually dynamically generate special access classes using System.Reflection.Emit. They take a bit longer to generate, but after that, access is lightning fast.

Fyodor Soikin
+2  A: 

Jon Skeet wrote a blog post about using Delegate.CreateDelegate() to speed things up:

http://msmvps.com/blogs/jon_skeet/archive/2008/08/09/making-reflection-fly-and-exploring-delegates.aspx

I don't know if it will work in Mono though.

Philippe Leybaert
A: 

Do you have to use magic strings? Another option is passing in a lambda expression, either by writing the lambda expression into your code or generating a member access lambda expression using Expression Trees. If you go the sxpression tree route, you can compile the expressions very easily and cache them for use.

Chris