Course contentsShow
← C
Lesson 640 of 1,2199. Structures and UnionsFree lesson

Structure holes and performance

Structure holes and performance

What you'll learn: How the C compiler inserts invisible gaps called "padding" into your structures to keep the CPU running at top speed.

The library shelf analogy

Imagine a library where every book is exactly 4 inches wide. The shelves are divided into 4-inch slots. If you have a 4-inch book, it fits perfectly. But what if you have a tiny 1-inch bookmark? You could cram four bookmarks into one slot, but the librarian (the CPU) prefers to give every item its own 4-inch slot. Why? Because it’s much faster to grab "Slot 3" than to grab "Slot 3, then shift through three bookmarks to find the right one."

In C, your computer's RAM is organized into "words" (usually 4 or 8 bytes). The CPU is optimized to grab data that starts exactly at the beginning of these words. This is called alignment.

The invisible gaps

When you create a struct, the compiler ensures every member starts at a memory address that the CPU likes. If a small variable is followed by a large one, the compiler inserts "padding"—invisible, wasted bytes—to push the next variable to a clean starting line.

struct FastFood {
    char ID;          // 1 byte
    // 3 bytes of invisible padding inserted here!
    int calories;     // 4 bytes
    char grade;       // 1 byte
    // 3 bytes of invisible padding at the end!
};

Even though you only defined 6 bytes of data (1 + 4 + 1), sizeof(struct FastFood) will likely return 12 bytes. The compiler added "holes" to ensure the int starts on a 4-byte boundary and that the entire structure fits neatly into the CPU's grid.

Why should you care?

Padding isn't just a fun fact; it affects performance and memory usage.

  1. Memory Waste: If you have an array of 1,000,000 such structs, you are wasting 6MB of RAM on empty holes.
  2. Cache Efficiency: The larger the struct, the fewer you can fit into the CPU's ultra-fast "Cache" memory. Smaller, tightly packed structs make your programs run faster.

To minimize holes, a common trick is to order your members from largest to smallest. By putting the int first and the chars at the end, the compiler can often pack them more tightly.

Key takeaway

The compiler adds invisible "padding" bytes to structures to align data with the CPU’s memory grid, prioritizing processing speed over saving RAM.