Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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?

If that's the case, would this create a huge performance overhead? Not memory, but runtime and GC wise.

like image 588
Joan Venge Avatar asked Mar 04 '10 20:03

Joan Venge


People also ask

How much memory does a class occupy in C#?

It is 1 byte generally.

How does inheritance work in memory?

In Inheritance, Memory is reserved by the concrete derived object only as it carries only the definition from the parent object. Classes are the template using which objects in memory are created. When Class B extends Class A , the object is created using the template B union A ( inherited elements from A ).

How is memory allocated in C#?

The Common Language Runtime (CLR) allocates memory for objects in these parts. Stack is a simple LIFO(last-in-first-out) structure. Variables allocated on the stack are stored directly to the memory and access to this memory is very fast, and its allocation is done when the program is compiled .

Does class acquire space in memory?

Once the object/instance of type class is define, the class member will occupy some space in memory. And the size of instance is equal to the sum of the size of members define in class.


2 Answers

Yes, it would create 'embedded' instances of A, B, C and D
No, it would not create instances of X, Y and Z (because they are interfaces)

There is no extra overhead for the memory allocation or GC (of ABCD) because the instance of E is allocated as 1 block. 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.

like image 139
Henk Holterman Avatar answered Oct 17 '22 21:10

Henk Holterman


It would create a single object - an instance of E - but that would include all the fields declared in the class hierarchy. (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 - i.e. it would still be a reference to the same object.

like image 7
Jon Skeet Avatar answered Oct 17 '22 19:10

Jon Skeet