Course contentsShow
← Rust
Lesson 1047 of 1,9109. Smart Pointers and Interior MutabilityFree lesson

Memory Layout Optimization

Arrange struct fields to minimize memory consumption and padding.

In this lesson, you will learn how to arrange struct fields to minimize memory consumption by reducing internal padding.

The Problem of Alignment

In Rust, the compiler must ensure that every type is stored at a memory address that is a multiple of its alignment requirements. For example, a u64 usually requires an 8-byte alignment. If you place a u8 (1 byte) followed by a u64, the compiler cannot place the u64 immediately after the u8 because that address might not be a multiple of 8. To fix this, the compiler inserts "padding" bytes—effectively wasted space—between the fields.

Illustrating the Waste

Consider this naive struct definition:

struct BadLayout {
    a: u8,   // 1 byte
    b: u64,  // 8 bytes (needs 8-byte alignment)
    c: u8,   // 1 byte
}

Because of the alignment rules, BadLayout will consume 24 bytes in memory. The compiler places a at offset 0, adds 7 bytes of padding so that b can start at offset 8, and then adds 7 more bytes of padding after c to satisfy the overall struct alignment.

Optimizing the Layout

You can significantly reduce the memory footprint by sorting your fields from the largest alignment requirements to the smallest. By grouping fields with similar sizes, you minimize the "gaps" required for alignment.

struct GoodLayout {
    b: u64,  // 8 bytes
    a: u8,   // 1 byte
    c: u8,   // 1 byte
             // 6 bytes of tail padding
}

By reordering, GoodLayout now consumes only 16 bytes. The u64 takes the first 8 bytes, and the two u8 fields occupy the next 2 bytes, leaving only 6 bytes of padding at the end. This simple reordering saved 8 bytes—a 33% reduction in size—without changing the logic of your program at all.

When designing high-performance data structures, especially those that will be stored in large arrays or sent over the network, always order your fields by size descending.

Key Takeaway: To minimize memory overhead, order your struct fields from largest alignment requirement to smallest to reduce internal padding.