Lesson 7 of 9 · 21m
Branch Prediction and Data-Dependent Control Flow
Why predictable if-statements are nearly free, mispredicts are expensive, and how branchless code helps only in the right situations.
A senior engineer once “optimized” validation code by sorting input so similar records arrived together. The algorithm did more work and still ran faster. That is the branch predictor in action: modern CPUs guess which way control flow will go and execute speculatively. A correct guess keeps the pipeline full; a wrong guess throws away work and restarts it.
The cost is pipeline disruption
A branch misprediction commonly costs on the order of 10-20 cycles, depending on the core and pipeline depth. One mispredict is nothing. Millions inside a hot loop become the profile.
for (size_t i = 0; i < n; i++) {
if (values[i] >= threshold) {
count++;
}
}If values are sorted or clustered, the predictor learns a stable pattern. If values are random around the threshold, the branch may be nearly unpredictable. The same instructions can have radically different performance because the input distribution changed.
Data layout affects control flow too
Branches are not only about the condition. If each element is a polymorphic object, the type distribution determines indirect branch prediction:
if type A: handle_A()
if type B: handle_B()
if type C: handle_C()Random interleaving of types stresses prediction. Grouping work by type — sometimes called batching — lets the predictor settle and often improves cache locality at the same time. This is why high-performance systems often transform event streams into homogeneous batches.
Branchless does not mean magically faster
You can replace some branches with arithmetic or conditional moves:
count += (values[i] >= threshold);Now the increment happens unconditionally. That can beat an unpredictable branch because there is no control-flow guess. But if the branch is highly predictable, branchless code may be slower: it performs work every iteration even when unnecessary.
A useful rule: keep predictable branches; consider branchless code for unpredictable branches with small bodies; restructure or batch when unpredictable branches guard expensive work.
Indirect branches are harder
Virtual calls, function pointers, and jump tables are indirect branches. They are harder to predict when targets vary. Devirtualization, sorting by type, or replacing polymorphism with data-driven tables can help hot loops. Do not erase useful abstraction in cold code; clarity matters where nanoseconds do not.
Compilers already know this game
Compilers use conditional moves, profile-guided optimization, and layout transformations when they can prove safety. With GCC or Clang, profile-guided optimization looks like this — and it is powerful only when training input represents production:
gcc -O3 -fprofile-generate bench.c -o bench
./bench-training-input
gcc -O3 -fprofile-use bench.c -o benchField notes
- Misprediction cost is caused by speculative work being discarded after the real branch outcome resolves.
- A branch that is 95% one way is usually cheap; a branch near 50/50 is the dangerous case.
- Exceptions and rare error branches should stay rare. Error handling in the hot path distorts prediction.
- Do not flatten logic into bit tricks before measuring. Branchless code can be harder to read and slower.
- Input distribution is part of program behavior. Benchmarks using uniform random data can mislead you.
Was this lesson helpful?