liveBook · Manning

Branch prediction

As explained in 100 Go Mistakes and How to Avoid Them

Branch prediction is a processor technique that forecasts the outcome of a conditional branch so subsequent instructions can be executed speculatively.

Branch prediction forecasts a conditional branch so the processor can execute likely-next instructions speculatively and preserve instruction-level parallelism. A predictor might observe a condition succeeding 99 of 100 times; when it is wrong, the processor flushes its pipeline, imposing a 10–20-cycle penalty. section 12.3

A common misconception is that sequential Go statements necessarily execute as an indivisible sequence:

  • The increment, condition check, and following increment can overlap when their dependencies permit it. section 12.3
  • A conditional instruction creates a control hazard when a later instruction depends on its outcome; prediction permits speculative execution rather than waiting. section 12.3
  • When diagnosing performance, distinguish a control hazard from a data hazard: changing dependencies can expose parallelism, but prediction addresses the branch decision itself. section 12.3
const n = 1_000_000
 
func add(s [2]int64) [2]int64 {
    for i := 0; i < n; i++ {       #1
        s[0]++                     #2
        if s[0]%2 == 0 {           #3
            s[1]++
        }
    }
    return s
}

Use this loop to inspect a conditional increment whose repeated outcome gives branch prediction an exploitable pattern. section 12.3

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Explains control hazards, prediction, pipeline flushing, and penalties, but stops short of predictor implementation details.
Examples
Uses Go increment loops, conditional checks, execution diagrams, and contrasting dependency structures.
What it assumes
Assumes basic instruction sequencing and Go familiarity while introducing instruction-level parallelism and processor hazards.
What you can do after
Diagnose performance effects by relating conditional branches and data dependencies to speculative execution and pipeline stalls.
How it connects
Connects branch prediction to instruction-level parallelism, control hazards, data hazards, and forwarding.

Also explained in

Compare how 2 books explain branch prediction →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Go Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.