Course contentsShow
← Rust
Lesson 99 of 1,9102. The Ownership ModelFree lesson

Memory Layout Predictability

Influence data layout through type ordering to minimize padding and maximize alignment.

In this lesson, you will learn how to arrange the fields in your structs to save memory and improve performance by minimizing "padding."

The Hidden Gap

When the CPU reads data from memory, it prefers accessing it in "aligned" chunks. If you have a u8 (1 byte) followed by a u64 (8 bytes), the computer cannot simply place the 8-byte integer immediately after the 1-byte integer. To ensure the u64 starts at an address divisible by 8, the compiler inserts 7 bytes of empty, unused space—called padding—between them.

This padding counts toward the size of your struct, consuming memory without holding any actual data.

Sorting for Efficiency

You can influence this layout simply by the order in which you define your fields. The rule of thumb is to order fields from the largest alignment requirement to the smallest.

Consider these two structs:

struct Inefficient {
    a: u8,   // 1 byte
    b: u64,  // 8 bytes
    c: u8,   // 1 byte
} // Total size: 24 bytes due to padding!

struct Efficient {
    b: u64,  // 8 bytes
    a: u8,   // 1 byte
    c: u8,   // 1 byte
} // Total size: 16 bytes!

In the Inefficient struct, the compiler adds padding after a to align b, and then adds more padding after c to ensure the total struct size is a multiple of the largest alignment. In the Efficient struct, by placing the 8-byte u64 first, the two u8 values fit snugly into the remaining space without triggering extra padding.

Why It Matters

Beyond just saving a few bytes, predictability in memory layout ensures your data structures remain compact. When your structs are smaller, more of them can fit into the CPU cache at once. Since accessing the cache is significantly faster than fetching data from main memory, this simple ordering trick can lead to meaningful performance gains in high-throughput applications.

Key Takeaway: Order your struct fields from largest alignment requirement to smallest to minimize internal padding and keep your data structures memory-efficient.