是实例方法复制在内存中的每个对象? [英] Are instance methods duplicated in memory for each object?

查看:145
本文介绍了是实例方法复制在内存中的每个对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要成为我的问题更清楚,如果你创建一个特定的类的数组,例如:

  ExampleClass中[ [试验=新ExampleClass中[5]; 



我知道的五个 ExampleClass中实例将创造每类每个变量的副本,但这些方法/函数在内存中重复5次,或做每个测试只是指向同一个代码库类?如果复制为每个类,那也只是浪费内存。


解决方案

加载到一个AppDomain每个类型都有一个方法表结构保存每个方法的类型定义,再加上从母公司获得的虚拟方法(通常对象),并通过任何实现的接口中定义的方法。



这方法表是由对象的每个实例指出。因此,每个实例的不重复所有由该类型定义与参考


$ B $方法,但指向该方法的表结构b

例如:

 公共MyClass类:IDisposable的
{
私有静态无效MyStaticMethod( )
{
// ...
}
公共无效MyInstanceMethod()
{
// ...
}
公共无效的Dispose()
{
抛出新NotImplementedException();
}
}

这MyClass的将有包括一个方法表:




  • MyStaticMethod

  • MyInstanceMethod

  • 的Dispose

  • 而从System.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.

解决方案

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:

You can check the whole article about method tables here

这篇关于是实例方法复制在内存中的每个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆