liveBook · Manning

Branch misprediction

As explained in High Performance Unity Game Development

A branch misprediction is an incorrect processor prediction of the outcome or execution path of a conditional branch.

A CPU predicts which path a conditional branch will take so its instruction pipeline can keep moving. If the prediction is wrong, the CPU discards work from the incorrect path, flushes the pipeline, and resumes on the correct path. Even predictable branches can slow tight loops; unpredictable patterns can hurt more. section 11.0 section 11.8

Listing 11.3 Simple branching test
int value = 0;
for(int i = 0; i < 1024; i++)
{
    value += i;
}
 
value = 0;
for(int i = 0; i < 1024; i++)
{
    if(i < 512)
    {
        value += i;
    }
}

Compare a loop that adds on every iteration with one that branches before adding on only half the iterations. Despite doing fewer additions, the branched loop can be slower; measure on the target device. section 11.0

For performance-sensitive game code:

  • Keep core functions simple and move conditional logic out of hot paths where practical. section 11.8
  • Reduce repeated checks by managing data lifetimes or separating groups such as alive and dead enemies; avoid optimizing without testing. section 11.8

How High Performance Unity Game Development covers it

How deep it goes
Traces prediction failures through pipeline flushing and contrasts measured loop performance, without detailing prediction algorithms.
Examples
Compares two 1024-iteration loops and discusses conditional checks in a game tick function.
What it assumes
Defines prediction and pipeline flushing from CPU instruction retrieval without stating required prior knowledge.
What you can do after
Evaluate branch costs by timing code on the target device and reduce unnecessary checks in hot paths.
How it connects
Links branch misprediction to branch prediction, CPU pipelines, and conditional branching.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of High Performance Unity Game Development. The section links point to the parts of the book it draws on.