实例方法是否在每个对象的内存中重复? [英] Are instance methods duplicated in memory for each object?
问题描述
要更清楚我的问题,如果你创建一个特定类的数组:例如
ExampleClass [ ] test = new ExampleClass [5];
我知道五个 ExampleClass
每个类的每个变量的副本,但是方法/函数在内存中重复5次,或者每个测试只指向同一个单独的类代码库?如果它为每个类复制,这只会浪费内存。
加载到AppDomain中的每种类型都有方法表结构,定义,以及从父(通常对象)派生的虚方法和任何实现的接口定义的方法。
此方法表由该对象的每个实例指向。因此,每个实例不会重复该类型定义的所有方法,但指向具有引用的此方法表结构。
例如:
public class MyClass:IDisposable
{
private static void MyStaticMethod )
{
// ...
}
public void MyInstanceMethod()
{
// ...
}
public void Dispose()
{
throw new NotImplementedException();
}
}
这个MyClass将有一个方法表, p>
- MyStaticMethod
- MyInstanceMethod
- 处置
- 和从System.Object派生的其他虚方法
看看方法表的好图: p>
您可以查看有关方法表的整篇文章此处
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屋!