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
