Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

d

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.

like image 217
jsmdnq Avatar asked Dec 05 '12 19:12

jsmdnq


2 Answers

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

like image 194
deadalnix Avatar answered Jan 03 '23 21:01

deadalnix


D uses two machine words in each class instance for:

  1. A pointer to the virtual function table. This contains the addresses of virtual methods. The first entry points towards the class's classinfo, which is also used by dynamic casts.

  2. The monitor, which allows the synchronized(obj) syntax, documented here.

These fields are described in the D documentation here (scroll down to "Class Properties") and here (scroll down to "Classes").

like image 37
Vladimir Panteleev Avatar answered Jan 03 '23 20:01

Vladimir Panteleev