Instance methods are duplicated in memory for each object?

To tell in more detail about my question if you create an array of a certain class: for example,

ExampleClass[] test = new ExampleClass[5]; 

I know that five instances of ExampleClass would create a copy of each variable for each class, but are the methods / functions duplicated 5 times in memory, or does each of the tests simply point to the same base code category? If it is duplicated for each class, it will be just a waste of memory.

+6
source share
1 answer

Each type loaded into AppDomain will have a Method Table structure that contains each method that determines the type, plus virtual methods received from the parent (usually Object ) and methods defined by any implemented interface.

This method table is indicated by each instance of this object. Therefore, each instance does not duplicate all the methods defined by this type, but points to this structure of method tables with a link .

For instance:

  public class MyClass : IDisposable { private static void MyStaticMethod() { // .... } public void MyInstanceMethod() { // .... } public void Dispose() { throw new NotImplementedException(); } } 

MyClass will have a method table, including:

  • Mystaticmethod
  • Myinstancemethod
  • Dispose
  • And other virtual methods derived from System.Object

Look at the diagram of the method table:

Method table diagram

You can check out the entire article on method tables here.

+8
source

Source: https://habr.com/ru/post/980453/


All Articles