4

I have a class in an SDK, for which every property I am in interested in calling. I know that the only way (I think the only way this is), is to use reflection, which most people claim as being slow etc (although I've seen articles which illustrate how in some cases it is not as slow as originally thought).

Is there a better way than to loop through and invoke each property in the target class?

Also, why is reflection deemed to be so slow?

GurdeepS
  • 65,107
  • 109
  • 251
  • 387

3 Answers3

1

It might be worth taking a looking at TypeDescriptors. As far as I am aware they have some performance benefits over using reflection and work in a slightly different way (they cache metadata for example). The MSDN article confused me in the way it describes how reflection is used by type descriptors, so you might need to find a more expansive explanation (therfore the 3rd link might be more helpful) .

The API for type descriptors is similar to that used for reflection.

Navigate to:

Soom loose answers to your questions then:

  1. Because of caching and a slightly different implementation to reflection TypeDescriptors my provide a performance improvement over relfection alone

  2. You may be able to retrieve the properties and (invoke/set/get?) the properties in one fell swoop. This may be a case of calling an invoke type method and writing a lambda statement to peform some action on the collection returned?

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
brumScouse
  • 3,166
  • 1
  • 24
  • 38
  • A lot of the reflection API caches results and intermediary results, the cache strategy had room for improvement in early versions but has gotten much better. Check it: http://msdn.microsoft.com/en-us/magazine/cc163759.aspx – marr75 Aug 02 '10 at 14:25
0

You can use reflection to generate C# code accessing directly to all properties you are interested in. That would be a faster way to perform the calls.

I think Reflection is not a bad option for you though. It's not that slow.

Pablo Santa Cruz
  • 176,835
  • 32
  • 241
  • 292
0

I would use reflection to generate the code that calls all the properties. Then you don't have to worry about reflection being slow.

ChaosPandion
  • 77,506
  • 18
  • 119
  • 157