Article: The Lost Art of Structure Packing
user1234
user1234 at 12.de
Tue Nov 3 13:08:29 UTC 2026
On Monday, 2 November 2026 at 12:22:38 UTC, Ogion wrote:
> On Monday, 2 November 2026 at 00:29:56 UTC, Richard (Rikki)
> Andrew Cattermole wrote:
>> I found this rather nice article about padding in structs, it
>> also applies to D.
>
> Maybe we need some way to allow the compiler rearrange the
> order of struct fields to optimally pack them, like it does
> with classes?
>
> ```D
> struct S {
> align (auto):
> byte a; // placed at offset 0
> int b; // placed at offset 4
> byte[3] c; // placed at offset 1
> }
> ```
>
> I’d even argue that auto-packing should be the default option.
This was suggested a few years ago (IIRC by Peter N.) when there
was an initiative to reduce heap memory usage of the DMD AST
(around 2019 I believe, about 50 related PRs).
The interface you propose is at first glance attractive (although
this has nothing to do about alignment, and rather the order) but
the cost on the compile-time would be nasty due to the
algorithmic complexity that is to find the best layout (basically
the algo is to test all the fields permutations, to associate
each one to a size, sort the results by size, print the number
one).
Other problem with the attribute solution is that this would be
executed for **each** new full recompilation. A better approach
would be to add a "-vfields-orders" switch that would suggest a
better layout. Then the programers can check, some times to
times, if everything is still optimal, without killing compile
times.
More information about the Digitalmars-d
mailing list