In C++, why can an if/else clamp over random floats run far slower than a loop that always stores std::clamp's result?
answer
- random data, random branch
- a store on only some paths
- the compiler may not invent writes
- select instead of jump
- sorted data predicts well
basics
~20 sThe if/else version writes only on out-of-range paths, so the compiler keeps a data-dependent branch per element, which random data mispredicts constantly. Always storing std::clamp's result lets it use min, max or select instructions and vectorise, leaving no branch to mispredict.
solid answer
~50 sA scalar clamp such as `if (v < lo) return lo; if (v > hi) return hi; return v;` usually compiles without branches already: for x86-64 Clang emitted `minss` and `blendvps` for floats and `cmov` for ints. The slow version is the **in-place** loop `if (x < 0) x = 0; else if (x > 1) x = 1;`, which writes only for out-of-range elements. The standard generally precludes the compiler from introducing stores the abstract machine would not perform, since another thread might be writing that memory, so the conditional store stays a branch, and on random data the predictor is often wrong, each miss costing a pipeline refill. Writing `x = std::clamp(x, 0.0f, 1.0f)` stores every element, so the loop becomes compares, selects and unconditional vector stores. On sorted data the branchy loop predicts well and gets fast again, and branchless scalar code can even lose to it.
code
cpp · 24 lines#include <algorithm>
#include <cstdio>
#include <vector>
// Branchy: the store happens only on the out-of-range paths.
void clampBranchy(std::vector<float>& v) {
for (float& x : v) {
if (x < 0.0f) x = 0.0f;
else if (x > 1.0f) x = 1.0f;
}
}
// Unconditional store: every element is written, whatever its value.
// std::clamp (C++17) requires !(hi < lo); NaN inputs are not supported.
void clampSelect(std::vector<float>& v) {
for (float& x : v) x = std::clamp(x, 0.0f, 1.0f);
}
int main() {
std::vector<float> a{-0.5f, 0.25f, 1.5f}, b = a;
clampBranchy(a);
clampSelect(b);
std::printf("%g %g %g | %g %g %g\n", a[0], a[1], a[2], b[0], b[1], b[2]);
}go deeper
Know that a CPU guesses which way an if goes, and that guessing wrong on unpredictable data is slow.
Explain why the conditional store keeps a branch, how std::clamp with an unconditional store becomes selects, and std::clamp's preconditions.
Prove it from the assembly and a test on production-shaped data, and know when branchless loses on predictable data.
Make data-dependent branches in hot loops a review item, backed by benchmarks that use realistic data distributions.
## Two loops that look the same ```cpp for (float& x : v) { if (x < 0.0f) x = 0.0f; else if (x > 1.0f) x = 1.0f; } // branchy for (float& x : v) x = std::clamp(x, 0.0f, 1.0f); // always stores ``` Both produce the same values. On a run over 4 million random floats in the range -1 to 2 on the author's arm64 machine at `-O2`, the first took about 20 ms and the second about 0.3 ms. The interesting part is why. ## Branch prediction in one paragraph A modern CPU fetches and executes instructions far ahead of the one it is retiring, so at every conditional branch it **predicts** the direction and keeps going. A correct guess is almost free. A wrong guess means throwing away the speculative work and refetching, which costs on the order of ten to twenty cycles on current desktop and server cores. Predictors learn patterns, so a branch that always goes one way, or follows a simple rhythm, is predicted well. A branch decided by **random data** is not: with values spread over -1 to 2, the branchy clamp's tests come out differently from element to element, and a large share of them miss. ## Why the compiler keeps the branch The C++ memory model is the reason the first loop cannot simply become the second: - The branchy loop writes `x` **only** when it is out of range. Turning that into an unconditional store would write to memory the abstract machine does not write. - The standard notes that transformations which **introduce assignments** to a potentially shared memory location are generally precluded, because another thread could legitimately be writing that element while this one only reads it. - So the compiler keeps a conditional store: a branch per element in scalar code, or per-lane branches around the stores in a vectorised loop, as the x86-64 output for the branchy loop shows. In the `std::clamp` loop every element is written anyway, so the compiler is free to compute the result with vector compares and selects (`cmpltps` and `blendvps` on x86-64, `fcmgt` and `bit` on arm64) and store whole vectors unconditionally. The x86-64 inner loop then has a single branch: the one that closes the loop. ## Branchless is not automatically faster | Data | Branchy loop | Always-store loop | Why | |---|---|---|---| | random | slow (about 20 ms) | fast (about 0.3 ms) | mispredictions versus none | | sorted | fast (about 1.4 ms) | fast (about 0.4 ms) | predictor learns long runs | | sorted, vectorisation turned off | about 1.4 ms | about 2.1 ms | branchless does both sides every time | The last row is the important counterexample: a branchless select always pays for computing both outcomes, while a well-predicted branch pays for one. Branchless code wins when branches are **unpredictable** or when it lets the loop **vectorise**; it can lose on predictable data in scalar code. The numbers are one machine's, the pattern is general. ## Using std::clamp correctly - `std::clamp` is in `<algorithm>` since **C++17** and returns `const T&` to one of its arguments; copy the result rather than holding the reference past the arguments' lifetime. - Its precondition is that `hi < lo` is false; violating it is undefined behaviour. - The standard notes that floating-point `T` works **if NaN is avoided**; with a NaN `v` both comparisons are false and the NaN comes back unchanged. - `std::min` and `std::max` combinations express the same thing and compile to the same instructions in this case. ## Reading the compiler output 1. Compile the hot function with `-O2 -S`, or paste it into a compiler explorer, for each target you ship. 2. In the loop body, look for conditional jumps (`ja`, `je`, `b.gt`, `cbz` and friends) that depend on the data rather than on the loop counter. 3. If they are there and the data is unpredictable, restructure so the work is unconditional: compute, then store every element. 4. Measure on production-shaped data: sorted test data can hide exactly the mispredictions that random production data exposes.
- Sorting the input first made the branchy clamp fast. Why is that usually not the fix?Sorting makes the branch predictable, so mispredictions vanish, but the sort costs O(n log n) and reorders data the program usually needs in its original order. It is a diagnostic: if sorting speeds the loop up dramatically, mispredictions were the cost, and the real fix is a branchless loop body.
- Why can the compiler turn a scalar clamp that returns a value into branchless code, but not the in-place loop?The function that returns a value only computes; choosing between `lo`, `hi` and `v` with a select changes no memory, so it is a pure optimisation. The in-place loop's branch guards a store, and making that store unconditional would introduce a write the program did not perform, which the memory model generally forbids for memory another thread could touch.
- Branchless code is always faster than code with branches.
- An if/else on a float is always compiled to a conditional jump.
- The compiler can always make a conditional store unconditional when that is faster.
- A mispredicted branch costs about the same as a correctly predicted one.
- std::clamp handles NaN inputs and a reversed lo and hi safely.