Are instance methods duplicated in memory for each object?

前端 未结 1 1299
梦谈多话
梦谈多话 2020-12-06 17:52

To be more clear about my question, if you create an array of a particular class: for example,

ExampleClass[] test = new ExampleClass[5]; 

相关标签:
1条回答
  • 2020-12-06 18:46

    Every type loaded into an AppDomain will have a Method Table structure that holds every method that type defines, plus the virtual methods derived from parent (typically Object) and the methods defined by any implemented interface.

    This Method Table is pointed by every instance of that object. So every instance does not duplicate all the methods defined by that type, but points to this method table structure with a reference.

    For example:

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

    This MyClass will have a method table including:

    • MyStaticMethod
    • MyInstanceMethod
    • Dispose
    • And other virtual methods derived from System.Object

    Have a look at nice diagram of method table:

    Method Table Diagram

    You can check the whole article about method tables here

    0 讨论(0)
提交回复
热议问题