11 Branching, performance, and extendibility
This chapter covers
- How branches affect performance.
- How branches affect code complexity.
- Reducing branches by reorganizing data.
- Hidden branches and how to avoid them.
Branches, such as if, switch, and the conditional operator ?:, can greatly affect both code complexity and performance.
Luckily, we can use data-oriented design to organize our data to eliminate branches by grouping similar objects into their own arrays. We already did this in chapter 6 by grouping alive and dead enemy indices into separate arrays. That allowed us to loop through our enemies without checking their status. The trade-off is that we now have more arrays to maintain, and we need to ensure indices move correctly between them. This adds some bookkeeping, but the benefit is that our runtime loops become simpler: instead of checking every enemy to see whether it is alive, we only loop through the enemies we already know are alive.
When it comes to code complexity, a good way to measure our codebase is to count its branches. The more branches a piece of code has, the more complex it is. For every branch we encounter, we need to understand the condition and determine what happens whether the condition is met or not.
For performance, branches in hot runtime code can slow things down, both because they add extra instructions and because the CPU may need to predict which path the code will take.