0

I'm reading the book CLR via C#, below is the descrption of what happens the first time a method is called: enter image description here

Just before the Main method executes, the CLR detects all of the types that are referenced by Main’s code. This causes the CLR to allocate an internal data structure that is used to manage access to the referenced types. In Figure 1-4, the Main method refers to a single type, Console, causing the CLR to allocate a single internal structure. This internal data structure contains an entry for each method defined by the Console type. Each entry holds the address where the method’s implementation can be found. When initializing this structure, the CLR sets each entry to an internal, undocumented function contained inside the CLR itself. I call this function JITCompiler.

I don't understand why CLR allocate a internal structure that contains an entry for each method, image a type has 100 methods and I just use one method, then the CLR will allocate the structure that contains 100 entries for 100 methods, isn't it very inefficient?

amjad
  • 3,048
  • 1
  • 11
  • 42
  • Does this answer your question? [How would the memory look like for this object?](https://stackoverflow.com/questions/58382702/how-would-the-memory-look-like-for-this-object) –  Jan 16 '21 at 22:26
  • When you create an instance of an object being of a type, you need to create all the object, so even if you do only one call to one method, you need to allocate all the memory required by the members variables as well as to compile all the methods code once. It is how .NET OOP works, because the CLR need to construct all the method tables, just for performance reasons, else it will be slower (.NET is not interpreted like JS/Python). See [vtables (Wikipedia)](https://en.wikipedia.org/wiki/Virtual_method_table) & [vtables (Learncpp.com)](https://www.learncpp.com/cpp-tutorial/the-virtual-table/). –  Jan 16 '21 at 22:34
  • A vtable of 100 entries times 16 bytes is only 1.6kb for that whole type, not for every object, and 100 functions is quite a lot. I believe it will be two pairs of IntPtr size, one for the method handle, one for the JIT stub location. Theoretically, private methods that are not referenced can be elided, but I don't think that's done. – Charlieface Jan 17 '21 at 02:21

0 Answers0