What is branch prediction, and how can writing branchless code improve C++ performance?
Last updated
Branch prediction is the CPU guessing a conditional's outcome to keep its pipeline full. A misprediction flushes speculative work and costs roughly 10-20 cycles.
Branchless code replaces unpredictable, data-dependent branches with arithmetic masks or conditional moves (
cmov), so there is nothing to mispredict.Predictable branches are already cheap, and branchless code always executes both sides, so it can be slower. Profile before hand-optimizing.