2

I'm working on a simple ORM library, quite simple in fact...

I have a query of type T

public IEnumerable<T> Query<T>(string query)

The method takes the T class, it gets the properties, loops through them and sets them accordingly

aProperty.SetValue(tmpGenericObjectOfTypeT, newValue, null);

My problem is that SetValue is incredibly slow, I saw two alternatives, using Reflection.Emit, or using delegates, unfortunately I have no idea how to do any of those.

As I've read, using delegates is a bit more elegant, and I'd like that solution, but I don't really know how to do it, I've searched and found a lot on how to call methods using Delegates, but not how to set properties...

gosukiwi
  • 1,569
  • 1
  • 27
  • 44
  • Unless you already know the name of your property delegates won't really help you. Since you want to do this at runtime you are stuck with either reflection or meta-programming via Reflection.Emit, or using ExpressionTrees. Neither are pleasant, but you if you want more performance then you are going to have to bite the bullet. – Josh May 16 '12 at 03:24
  • Looks like emit it is. Thanks. Wouldn't it work if I make them implement a base class, so I know the name of the delegate? – gosukiwi May 16 '12 at 03:25

2 Answers2

1

Dynamic methods or expression trees which know how to get/set the property are the way to go here. Fast and easy.

  • Examine the interface of your type using reflection
  • Build getter/setter Actions/Funcs and cache them in an object which relates them to the original type.
  • Used cached getters/setters in subsequent operations.

You should see at least a 20x performance improvement over reflection (if not more like 50-100x).

Tim M.
  • 53,671
  • 14
  • 120
  • 163
  • Looks like Expression Trees don't use Emit, that would be a nice option for me as I have no idea hwo to use it. Thanks a lot! Any tips on where I can read more about expression trees? – gosukiwi May 16 '12 at 12:04
  • The link I included is a good start, and there are at least a few expression tree gurus here on SO. If you can't find an existing answer, just open a new question. – Tim M. May 16 '12 at 14:40
0

HyperDescriptor works pretty well (ReflectionEmit based). http://www.codeproject.com/Articles/18450/HyperDescriptor-Accelerated-dynamic-property-acces

The "delegate" method is probably referring to expression trees?

Kenneth Ito
  • 5,201
  • 2
  • 25
  • 44
  • If you go with HyperDescriptor on .net4 this might be needed. http://stackoverflow.com/questions/3105763/does-hyperdescriptor-work-when-built-in-net-4 – Kenneth Ito May 16 '12 at 03:35