Course contentsShow
← Rust
Lesson 1700 of 1,91015. Performance and Architectural EngineeringFree lesson

Optimizing Field Ordering for Alignment

Reorder struct members to minimize padding bytes and improve memory density.

In this lesson, you will learn how to reduce the memory footprint of your Rust structs by reordering fields to minimize implicit padding.

The Cost of Alignment

In Rust, the compiler enforces alignment rules to ensure that data types can be accessed efficiently by the CPU. For instance, a u64 typically requires 8-byte alignment. If you place a 1-byte u8 before an 8-byte u64, the compiler must insert 7 bytes of "padding" after the u8 to ensure the u64 starts at a memory address divisible by 8.

Consider this inefficient struct:

struct Inefficient {
    a: u8,   // 1 byte
    b: u64,  // 8 bytes (requires 7 bytes padding before it)
    c: u8,   // 1 byte
}

In the structure above, the layout is: [a][padding x 7][b][c][padding x 7]. This struct occupies 24 bytes, even though the data itself only totals 10 bytes. The trailing padding exists because the struct’s total size must be a multiple of its largest alignment requirement.

Strategy: Sorting by Size

The most effective way to eliminate this waste is to order your fields by their alignment requirements in descending order. By placing the largest types first, you ensure that smaller types can fill the "gaps" without triggering alignment boundaries.

Refactored for efficiency:

struct Optimized {
    b: u64,  // 8 bytes
    a: u8,   // 1 byte
    c: u8,   // 1 byte
             // 6 bytes padding here
}

In this version, the layout is [b][a][c][padding x 6]. The total size drops from 24 bytes to 16 bytes. By simply moving the u64 to the top, we saved 8 bytes per instance.

When dealing with structs containing thousands or millions of instances, these savings compound significantly, improving cache locality and reducing the memory pressure on your system. You can verify your struct sizes using std::mem::size_of::<T>(). For complex structs, consider using the field-reorder crate or the #[repr(packed)] attribute (with extreme caution), though manual reordering remains the standard practice for performance-critical systems.

Key Takeaway: To minimize memory waste, always sort your struct fields from largest alignment requirement to smallest to eliminate unnecessary implicit padding.