Course contentsShow
← C
Lesson 1190 of 1,21916. Practice and ProjectsFree lesson

Loop unrolling explained

Loop unrolling explained

What you'll learn: How to speed up your programs by reducing the "hidden" work your computer does during every loop iteration.

When we write a for loop, we focus on the code inside the curly braces. However, the computer spends extra energy on "loop overhead"—checking if the condition is still true (is i < 100?) and incrementing the counter (i++). While this happens in nanoseconds, doing it millions of times adds up.

The assembly line analogy

Imagine you are at a pizza shop. A customer orders four pizzas.

  1. The "Loop" way: You make one pizza, walk to the oven, check the order ticket to see if you need more, walk back, and repeat this four times.
  2. The "Unrolled" way: You clear a large space on the counter, prep all four pizzas at once, and walk to the oven just once.

By doing more work per "trip," you waste less time checking the ticket and walking back and forth.

Unrolling in code

Loop unrolling is a technique where you manually repeat the loop body multiple times to reduce the total number of iterations.

Suppose you want to add values to an array:

// Standard Loop
for (int i = 0; i < 8; i++) {
    data[i] = i * 2;
}

// Unrolled Loop (by a factor of 4)
for (int i = 0; i < 8; i += 4) {
    data[i]     = i * 2;
    data[i + 1] = (i + 1) * 2;
    data[i + 2] = (i + 2) * 2;
    data[i + 3] = (i + 3) * 2;
}

In the first example, the computer performs 8 comparisons and 8 increments. In the unrolled version, it only performs 2 comparisons and 2 increments to achieve the exact same result.

Why do this?

Modern CPUs are designed to execute multiple instructions simultaneously (instruction-level parallelism). When you unroll a loop, you provide the CPU with a longer sequence of independent tasks, allowing it to stay busy rather than waiting on the result of a "counter check."

A word of caution: You don't always need to do this manually! Modern C compilers are incredibly smart and will often unroll loops for you if you enable optimization flags (like -O2 or -O3). However, understanding the logic helps you write high-performance code when the compiler needs a nudge.

Key takeaway

Loop unrolling reduces program overhead by doing more work per iteration and performing fewer conditional checks.