views:

70

answers:

3

I have a list of keyvaluepair(string,string) first string is something like class.property, second string is the value to assign to that class.property.

I'm currently looping through that list and by using reflection I set every value.

it work, but my question is there a faster way to do this?

+3  A: 

If you're using the same property repeatedly (e.g. against a variety of target objects), it's faster to build a delegate out of the setter using Delegate.CreateDelegate and use that. However, I'd only do that when I'd profiled it and found that this was a bottleneck. It happened to make a big difference against my protocol buffer implementation, but that really needs to be as fast as possible, so I'm happy to apply a bit of micro-optimisation.

Jon Skeet
interesting, reading that blog now
Fredou
sadly, my list of keyvaluepair can contains nearly a hundred of item and each one is calling one unique class.property. that link is bookmarked because I'm pretty sure that I'm going to use it later on, thanks
Fredou
If you're only going to use each property once, then doing it directly with reflection is going to be about as fast as it gets.
Jon Skeet
you got the green check for the comment above :-)
Fredou
A: 

If you need to set the same property, or properties on the same type, more than once, cache your Type and PropertyInfo's. It is very easy stuff to cache - and examining the types is what typically takes the time in reflection scenarios.

If you can use C# 4 for this, you might be able to come up with a faster solution using dynamic. (I have seen the .NET 3.5 tag, just thought I would mention it).

driis
Dynamic won't (easily) work here - dynamic typing in C# 4 lets you easily use a name which is known at compile-time against a type which doesn't statically export it - but you'd have to do a fair amount of work to do this against a name which is only available via a string. Admittedly you could create a Python script and then run it :)
Jon Skeet
A: 

If all items in your list of properties are known, and of a rather manageable size, you could make a switch for it. The code would be less clean, but easier to understand and quicker to execute. Since they're strings in the input-end, both approaches are as prone to human error.

David Hedlund