Featured image of post [C#] 왜 리플렉션은 느린가?

[C#] 왜 리플렉션은 느린가?

Reflection이 느린 이유

배경

  • CLR Type System Design Goals
    • Goals
      • Accessing information needed at runtime from executing (non-reflection) code is very fast.
    • Non-Goals
      • All uses of reflection are fast.
  • EEClass
    • MethodTable data are split into “hot” and “cold” structures to improve working set and cache utilization. MethodTable itself is meant to only store “hot” data that are needed in program steady state. EEClass stores “cold” data that are typically only needed by type loading, JITing or reflection. Each MethodTable points to one EEClass.

어떤 동작때문에 느린것인가?

  • Fetching the Method information
  • Argument Validation and Error Handling
  • Security Checks

Reflection에는 어느정도의 비용이 들어 가는가?

Reading a Property (‘Get’)

MethodMeanStdErrScaledBytes Allocated/Op
GetViaProperty0.2159 ns0.0047 ns1.000.00
GetViaReflection197.9258 ns0.2704 ns923.080.01

Writing a Property (‘Set’)

MethodMeanStdErrScaledBytes Allocated/Op
SetViaProperty1.4043 ns0.0200 ns6.550.00
SetViaReflection287.1039 ns0.3288 ns1,338.99115.63