Course contentsShow
← C
Lesson 574 of 1,2198. Memory ManagementFree lesson

Performance cost of unaligned access

Performance cost of unaligned access

What you'll learn: Why the way you arrange variables in a struct can significantly impact how fast your CPU processes data.

The CPU’s Reading Habit

We often imagine the CPU reading memory one byte at a time, like a person reading a book letter by letter. In reality, the CPU reads memory in "chunks"—usually 4 or 8 bytes at a time (called a word).

Imagine a library where you can only check out books in stacks of four. If the information you need is all contained within one stack, you make one trip. But if the information starts at the end of Stack A and finishes at the beginning of Stack B, you have to carry both stacks to your desk, pick out the relevant pages, and piece them together.

In programming, this "extra trip" is exactly what happens with unaligned access.

How Padding Slows You Down

Computers prefer data to start at memory addresses that are multiples of their own size. A 4-byte int wants to start at an address divisible by 4. If you force an int to start at an awkward address (like address 3), it "straddles" the boundary between two memory words.

To read that single integer, the CPU must:

  1. Fetch the first word.
  2. Fetch the second word.
  3. Shift and mask the bits to glue the two halves together.
struct PerformanceTrap {
    char a;      // 1 byte
    // The compiler inserts 3 bytes of "padding" here 
    // to keep 'b' aligned to a 4-byte boundary.
    int b;       // 4 bytes
    char c;      // 1 byte
    // 3 more bytes of padding follow to keep the struct size 
    // a multiple of 4.
};

If you tell the compiler to "pack" this struct (removing the padding), you save a few bytes of RAM, but you force the CPU to perform that "double-trip" every time you access b. In a loop running millions of times, this overhead adds up to a massive performance hit.

The Cost of Complexity

Modern CPUs are smart and try to hide this cost, but unaligned access still consumes more power and can even cause a program to crash on certain hardware architectures (like some ARM chips) that strictly forbid it. By letting the compiler insert padding, you trade a tiny bit of memory for a lot of speed.

Key takeaway

Unaligned data forces the CPU to perform multiple memory fetches and complex bit-shifting to read a single value, leading to slower execution and higher power consumption.