Zig Is Better Than Rust At Storing Structs In A List.
struct Info {
age: u64,
isAdult: bool,
isAlive: bool,
};
Above is a code of snippet from the Rust programming language. If I were to ask you to guess the amount of bytes it would take to store one of these structs in memory, what would be your answer?
If you know how much storage each data type takes, you would probably say bool
(1 byte) + bool
(1 byte) + u64
(64 bits), and that would be around 10 bytes or 80 bits.
But that’s not the case because of Alignment and Padding. Since a structs alignment is equal to the amount of bytes the largest element takes.
So in our case it won’t be 2 bits for two bool
types but instead it’ll be 8 bytes, 6 bytes are just for unnecessary padding. That is 16 bytes in total.
MultiArrayList
Zig’s built-in feature called MultiArrayList provides a way to efficiently store structs in a linear list.
Instead of storing the struct in a single array, it stores each element in a different array. Since all the elements in the array have the same data type and there are no structs, it doesn’t have to make up for Alignment or Padding.