Imagine I have two classes, class1 and class2.
Class1 inherits from baseClass, which looks like so:
baseClass
{
private Int64 one;
protected Int64 two;
public Int64 three;
}
and class1 looks like this
Class1 : baseClass
{
private Int64 four;
protected Int64 five;
public Int64 six;
}
and class2 looks like this:
Class2
{
private Int64 one;
protected Int64 two;
public Int64 three;
private Int64 four;
protected Int64 five;
public Int64 six;
}
If I were to create arrays of 10k of each class, which would be larger? Would the class1 array be larger because class1 would also contain some sort of meta data to do with baseClass? Otherwise their properties are identical, so technically they should be the same.
Given two arrays of reference types, that is:
The arrays will be exactly the same size. The elements of the arrays are just references, and a reference is always the same size, regardless of the object to which it’s referring. A reference is 4 bytes in the 32-bit runtime, and 8 bytes in the 64-bit runtime.
As for the class instances, I would expect them to be identical in size, as well. The class instance itself only holds the data for the class, and a small amount of other data that includes a reference to the type for that class. The class instance itself doesn’t “know” that it’s a derived class. That information is held by the type.
So, the type information for
Class1might be slightly larger than the type information forClass2, but instances of those two classes will occupy the same amount of memory.When all’s said, using
Class1, which inherits frombaseClass, is going to cost you a handful of bytes more than usingClass2, because you have type information for two classes. But it really is just a few bytes more–whatever the overhead is for the class metadata. It does not cost you anything extra for each class instance.