How do branch prediction and misprediction affect a hot loop, and when can restructuring or [[likely]]/[[unlikely]] help?
Show answer and explanation
Processors predict control flow so instructions after a likely branch can execute speculatively; a wrong prediction discards that work and redirects the pipeline. A cheap, data-dependent, unpredictable branch repeated in a hot loop can therefore dominate, but its cost depends on the microarchitecture and surrounding work. Confirm it with representative benchmarks, profiles, and branch-miss counters. Restructuring data, separating common paths, vectorizing, or computing a safe branchless form can help, but may execute more work or introduce different undefined behavior. The standard attributes [[likely]] and [[unlikely]] express an optimization hint, not a probability or guarantee, and stale hints can hurt; profile-guided optimization is often stronger evidence.
Processors predict control flow so instructions after a likely branch can execute speculatively; a wrong prediction discards that work and redirects the pipeline. A cheap, data-dependent, unpredictable branch repeated in a hot loop can therefore dominate, but its cost depends on the microarchitecture and surrounding work. Confirm it with representative benchmarks, profiles, and branch-miss counters. Restructuring data, separating common paths, vectorizing, or computing a safe branchless form can help, but may execute more work or introduce different undefined behavior. The standard attributes [[likely]] and [[unlikely]] express an optimization hint, not a probability or guarantee, and stale hints can hurt; profile-guided optimization is often stronger evidence.
Connect the conclusion directly to the type, lifetime, ownership, overload-resolution rule, or library contract present in the question. State implementation dependence or a violated precondition explicitly instead of merely guessing output.