简体   繁体   English

在.NET中具有深度继承的类的内存分配

[英]Memory allocation for a class that has deep inheritance in .NET

If I have classes A, B, C, D, E , and interfaces like X, Y, Z , and model a system like: 如果我有类A, B, C, D, E ,以及X, Y, Z和模型等接口,那么系统就像:

class B : A, X
class C : B, Y
class D : C, Z
class E : D

If A is an abstract base class and E is the class of interest, when I create an instance of E, would it in turn create instances of A, B, C, D, X, Y, Z in addition to E ? 如果A是一个抽象基类和E是类感兴趣,当我创建E的情况下,将它反过来创建的实例A, B, C, D, X, Y, Z除了E

If that's the case, would this create a huge performance overhead? 如果是这种情况,这会产生巨大的性能开销吗? Not memory, but runtime and GC wise. 不是内存,而是运行时和GC明智的。

Yes, it would create 'embedded' instances of A, B, C and D 是的,它会创建A,B,C和D的“嵌入式”实例
No, it would not create instances of X, Y and Z (because they are interfaces) 不,它不会创建X,Y和Z的实例(因为它们是接口)

There is no extra overhead for the memory allocation or GC (of ABCD) because the instance of E is allocated as 1 block. 内存分配或GC(ABCD)没有额外的开销,因为E的实例被分配为1个块。 Any runtime overhead would entirely depend on the constructors involved. 任何运行时开销都完全取决于所涉及的构造函数。

There will always be a chain of contructors (from E to A) being executed, possibly the default constructor but it's also possible to call multiple constructors at 1 level. 将始终存在一系列构造函数(从E到A),可能是默认构造函数,但也可以在1级调用多个构造函数。

It would create a single object - an instance of E - but that would include all the fields declared in the class hierarchy. 它将创建一个单个对象 - 一个E实例 - 但它将包括在类层次结构中声明的所有字段。 (Interfaces can't declare fields, so they're irrelevant to the data within the object itself.) It's only fields (and any attributes affecting layout, admittedly) that contribute to the memory taken up by an object. (接口不能声明字段,因此它们与对象本身内的数据无关。)只有字段(以及影响布局的任何属性,不可否认)才会对对象占用的内存产生影响。

The reference to the instance of E could be "converted" to a reference of type A, B, C, D, X, Y or Z as an identity-preserving reference conversion - ie it would still be a reference to the same object. 对E实例的引用可以“转换”为类型A,B,C,D,X,Y或Z的引用,作为保持身份的引用转换 - 即它仍然是对同一对象的引用。

The inheritance extends the Type and does not create instances. 继承扩展了Type ,但不创建实例。 You have one single instance of E that includes the data defined by A, B, C, D and E. It provides methods and property accessors defined by these classes and the interfaces X, Y, and Z. 您有一个E实例,其中包含由A,B,C,D和E定义的数据。它提供了由这些类以及接口X,Y和Z定义的方法和属性访问器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM