In this lesson, you will learn how to manually calculate the precise memory footprint and alignment requirements of your Rust structs to optimize high-performance data structures.
Understanding Memory Layout
Every Rust struct has two primary constraints: size (the number of bytes it occupies) and alignment (the memory boundary at which it must start). The Rust compiler arranges fields to minimize memory waste, but it must adhere to the rules of your target CPU architecture, which typically requires a type of size N to be stored at an address divisible by N.
The Calculation Process
Consider this struct on a standard 64-bit architecture:
struct SensorData {
active: bool, // 1 byte
value: u64, // 8 bytes
flag: u8, // 1 byte
}
If you naively add the bytes, you might expect 10 bytes. However, the CPU accesses memory in chunks. An u64 must start at an address divisible by 8. To satisfy this, the compiler inserts padding:
active(1 byte) is placed at offset 0.- The compiler inserts 7 bytes of padding so that
valuecan start at offset 8. value(8 bytes) occupies offsets 8 through 15.flag(1 byte) is placed at offset 16.- To satisfy the struct's overall alignment requirement (which matches the largest field,
u64, requiring an alignment of 8), the compiler adds 7 more bytes of padding at the end to round the total size to a multiple of 8.
The total size of this struct is actually 24 bytes, even though it only holds 10 bytes of actual data.
Optimization Strategy
To reduce the footprint, you can reorder fields from largest to smallest. By placing the u64 first, you eliminate the initial padding:
struct OptimizedSensorData {
value: u64, // 8 bytes
active: bool, // 1 byte
flag: u8, // 1 byte
// 6 bytes of tail padding remain
}
Reordering reduces the size to 16 bytes. In high-throughput systems, this 33% reduction significantly improves cache locality and lowers memory pressure.
Key Takeaway: The size of a struct is determined by the sum of its fields plus the padding injected to satisfy the alignment requirements of the largest individual field.