0

Possible Duplicate:
Is Reflection really slow?

People often tell me that the performance of reflection is poor, but why? I've searched for detail about reflection, wondering about its mechanisms and the secret of the "poor performance", but got nothing useful. Can somebody show me the key or some information? The more detailed, the better.

Community
  • 1
  • 1
yman
  • 3,385
  • 3
  • 15
  • 9
  • 7
    Is the performance of reflection poor? Compared to what? There are several good Q's on Stack Overflow about whether or not reflection really is "slow". Suggest you read them, then formulate a more specific question. – Eric J. Aug 28 '12 at 03:35
  • You need to prove it first before asking why. – Cheng Chen Aug 28 '12 at 03:39
  • 1
    @EricJ.: Compared to most other code. Yes, it is poor. It takes a lot of cycles compared to similar operations. I agree with you though; this question is far too broad to be useful. – Ed S. Aug 28 '12 at 03:47
  • @StaffordWilliams:smells not constructive to me, so that's how I voted. – John Saunders Aug 28 '12 at 04:05

1 Answers1

8

Two aspects. First is finding the metadata, it is only fast the second time you look it up. The first time you tend to have to pay for a handful of page faults to get the data from the assembly into RAM. It is cached after that. You tend to care about (or measure) the first time.

Second one is that the directly calling a method or accessing a field or property is so incredibly fast. It doesn't typically cost more than one or two cpu cycles. Including none when the method can be inlined or the field access can be overlapped with another instruction. Reflection will always compare poorly against that, it takes hundreds of instructions.

Reflection is a suitable solution when other code takes a substantial amount of time so the cost of reflection is a small factor. Which includes anything that involves I/O like file formats and dbase mappings. And code that runs at human time, like designers and compilers.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • 1
    Heh; just to add a though on your last paragraph - as someone who does a lot of work on things "that involves I/O like file formats and dbase mappings" - oddly enough, I feel the exact opposite; because these things can be called at high frequency, it can often be **where reflection performance shows itself to be slow** - hence why protobuf-net and dapper-dot-net make use of cached meta-programming via `ILGenerator`, etc. – Marc Gravell Aug 28 '12 at 06:25
  • Thanks Passant,I ran some codes to see the difference between them,and yes the directly calling is faster,but as you said,reflection is still a reasonable solution because it's fast enough most time. – yman Aug 29 '12 at 01:50