Search code examples
d

Why are empty classes 8 bytes and larger classes always > 8 bytes?


class foo { }

writeln(foo.classinfo.init.length); // = 8 bytes

class foo { char d; }

writeln(foo.classinfo.init.length); // = 9 bytes

Is d actually storing anything in those 8 bytes, and if so, what? It seems like a huge waste, If I'm just wrapping a few value types then the the class significantly bloats the program, specifically if I am using a lot of them. A char becomes 8 times larger while an int becomes 3 times as large.

A struct's minimum size is 1 byte.


Solution

  • In D, object have a header containing 2 pointer (so it may be 8bytes or 16 depending on your architecture).

    The first pointer is the virtual method table. This is an array that is generated by the compiler filled with function pointer, so virtual dispatch is possible. All instances of the same class share the same virtual method table.

    The second pointer is the monitor. It is used for synchronization. It is not sure that this field stay here forever, because D emphasis local storage and immutability, which make synchronization on many objects useless. As this field is older than these features, it is still here and can be used. However, it may disapear in the future.

    Such header on object is very common, you'll find the same in Java or C# for instance. You can look here for more information : http://dlang.org/abi.html