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

Reducing branching in tight loops

Reducing branching in tight loops

What you'll learn: How to replace if statements with mathematical expressions to help the CPU process data faster.

The problem with "Roadblocks"

Modern CPUs are like high-speed trains. They don't just wait for an instruction to finish; they try to predict the future. When your code reaches an if statement (a branch), the CPU guesses which path it will take so it can keep moving at full speed.

If the CPU guesses wrong, it has to "slam on the brakes," throw away the work it started, and go back to the start of the other path. In a "tight loop"—one that runs millions of times—these wrong guesses (branch mispredictions) act like constant red lights, significantly slowing down your program.

Branchless thinking

To optimize, we try to make the code "linear." Instead of asking the CPU to make a choice, we use math to achieve the same result.

Imagine you want to sum only the positive numbers in an array. Normally, you’d use an if (val > 0). Instead, you can use a boolean comparison as a multiplier. In C, a true comparison evaluates to 1 and a false one to 0.

// Version A: With Branching
for (int i = 0; i < size; i++) {
    if (data[i] > 0) {
        sum += data[i];
    }
}

// Version B: Branchless (Faster in tight loops)
for (int i = 0; i < size; i++) {
    // If data[i] > 0 is false (0), we add (0 * data[i])
    // If data[i] > 0 is true (1), we add (1 * data[i])
    sum += (data[i] > 0) * data[i];
}

Why this works

In Version B, there are no decisions for the CPU to make. The train stays on a single, straight track. It simply performs the multiplication and addition every single time. While multiplication might seem "slower" than a simple jump, it is often much faster than the penalty of a wrong guess.

This technique is especially powerful when your data is unpredictable (like random numbers), where the CPU’s "branch predictor" is most likely to fail.

Key takeaway

Replace conditional logic with mathematical formulas to keep the CPU's execution pipeline moving without interruption.