CLR Reflection and Metadata management - where is the truth?

85 Views Asked by At

I always thought that Reflection in CLR loads metadata for types on demand, when you actually request needed information. And then it is cached, and all subsequent calls will be cheaper. At least, that's what some articles on the internet told me.

However recently I read that when an assembly is loaded in CLR - all metadata for all types shall be loaded from metadata tables as well. Which makes sense.

However, those two statements contradict each other and I am now very confused.

If CLR loads metadata with assemblies - then why would Reflection need to load anything? It would be fetching the info from the cache, wouldn't it? And if it does - then all the articles about how metadata loading/caching is a slow-performance-factor for Reflection - are lying?

Let's say I create an instance of type A in some method, and that type references another type B. I then want to analyze type B, and get information about all its fields. Will it involve loading any metadata? Or is it already loaded and cached?

Or another case - if in C#, default GetHashCode implementation for ValueType is called, which under the curtains in some cases uses Reflection on CLR side - will it fetch already cached data?

Please help me to understand how it all works and finally have a good night sleep.

1

There are 1 best solutions below

3
Charlieface On

It depends what you call "metadata". When an assembly is loaded then the whole assembly is parsed, and basic structures are created to store information about each type so that the JITter knows how to execute the code. The code itself is not JITted yet though.

However, reflection uses many other structures that are not necessary for loading and executing the assembly. For example, it may create TypeInfo and FieldInfo objects, or arrays of CustomAttribute. It's these that are cached when reflection is used for the first time.