Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
134 views
in Technique[技术] by (71.8m points)

c# - Are instance methods duplicated in memory for each object?

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

ExampleClass[] test = new ExampleClass[5]; 

I know the five ExampleClass instances would create a copy of each variable for each class, but are the methods/functions duplicated 5 times in memory, or do each of the tests just point to the same single class codebase? If it duplicated for each class, that would just be a waste of memory.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...