反转结构体字段顺序可节省空间

#Tech

本文探讨了编译器在处理结构体和枚举类型时,对内存布局和对齐方式可能造成的空间浪费问题。

通常情况下,结构体中的字段按照顺序排列,编译器会根据每个字段的对齐需求调整结构体的大小,导致空间浪费。

通过将枚举类型(如 Option)的标签(tag)从前面移动到后面,可以避免不必要的对齐,显著减少内存占用。

Swift 采用了一种特殊的布局算法,能够有效地减少结构体嵌套带来的空间浪费,而其他语言则可以通过调整字段顺序实现类似的效果。

查看原文开头(英文 · 仅前 3 段)

The short version of this shower thought: storing the tags for sum types after the payload rather than before can save a surprising amount of space.

The long version needs some context.

A pointer has alignment A if ptr % A == 0. Eg a pointer to address 564 has alignment 4, because 564 % 4 == 0. But it does not have alignment 8 because 564 % 8 == 4.

※ 出于版权考虑,仅引用前 3 段。完整内容请阅读原文。

阅读原文 ↗