Chapter 11: Branching, performance, and extendibility
The introduction explains how branches affect code complexity and runtime performance, and how grouping data can remove checks from hot loops.
After this chapter you will be able to
- Branch count and complexity. Explain why adding branches makes code harder to understand and debug, using the contrasting Tick() examples.
- Branch costs in hot code. Describe how branch prediction can penalize runtime code and why even an easily predicted branch should not be assumed free.
- Grouped enemy status arrays. Explain how separating alive and dead enemy indices removes status checks from the enemy loop, and state the resulting bookkeeping trade-off.
- Branch result predictability. Explain that a predictable pattern of branch results makes it easier for branch prediction to guess which branch will be taken than random results do.
- Branch outside enemy movement. Explain why the paralysis check should sit outside moveEnemy() rather than make moveEnemy() sometimes return without moving an enemy.
- Validation at system boundaries. Distinguish useful validation at system edges from repeated early-return checks in controlled runtime code, and explain how to respond if supposedly valid data proves invalid.
- Unity object null semantics. Explain why checking a GameObject or MonoBehaviour for null involves more than checking an ordinary C# reference.
- Runtime null-check cost. Describe the section's comparison of GameObject access with and without a null check and its performance result.
- One-time asset reference checks. Explain why references assigned in the Unity Editor need not be checked for null throughout gameplay, and describe when to check downloaded assets instead.
- Zero tolerance for development errors. Explain why an error should stop play during development rather than remain a console message that the team can ignore.
- Owned GameObject lifetimes. Explain why controlling when GameObjects are created and deallocated can make null checks unnecessary, including for dynamically instantiated objects. Describe how avoiding those checks helps performance, readability, and debugging.
- Callbacks outliving GameObjects. Explain how a coroutine or static event callback can still reference a GameObject after it is destroyed, even though Unity often stops coroutines owned by the destroyed object.
- Explicit control of ticking. Justify using owned timers and a Tick() function instead of fire-and-forget behavior in the book’s frame-by-frame gameplay systems, and describe what happens when a system is no longer active.
- Data separated by branch result. Explain how separate index arrays reduce branch checks, using alive and dead enemies as the example.
- Unused pool index search. Describe how an array of unused pool indices changes the search for a free GameObject, including what happens when none are available.
- Distinct scripts for menu variants. Explain why the settings, in-game, and game-over top bars should use separate scripts rather than one TopBar script full of branches.
- Isolated fixes and shared styling. Describe how separate menu scripts limit the effects of fixes and QA retesting, while shared assets and data keep the UI visually consistent.
- Hidden branches from default parameters. Explain how a default value for moveEnemy()’s enemyParalyzed boolean lets existing calls omit the argument while concealing a branch, and why changing that default could break those calls.
- Branch costs and hidden checks. Explain why branches can hurt performance and readability, and identify default parameter values as a possible source of hidden branch checks.
- Unity GameObject null checks. Explain why repeated GameObject null checks cost extra work in Unity and describe the approaches given for limiting them safely.
- Separation instead of repeated branching. Describe how separating enemy and pool data, and splitting shared UI elements, avoids checks and limits the effects of changes.
What it builds on
- Using the AliveEnemyIndices array (chapter 6) · The use of the AliveEnemyIndices array.
- Tick() - Handling frame-by-frame gameplay (chapter 4) · The use of Tick() for frame-by-frame gameplay.
- Setting the pool size (chapter 10) · Assumes the Board has a GameObject pool.
- Hiding removed enemies (chapter 10) · Builds on the Board’s handling of removed enemies.
- Separating asset data from logic (chapter 8) · The distinction between asset data and menu logic.
Section by section
Introduction
The introduction explains how branches affect code complexity and runtime performance, and how grouping data can remove checks from hot loops.
- Branch count and complexity: Explain why adding branches makes code harder to understand and debug, using the contrasting Tick() examples.
Why it matters: Branch count offers a practical way to spot code that will be harder to follow and debug. - Branch costs in hot code: Describe how branch prediction can penalize runtime code and why even an easily predicted branch should not be assumed free.
Why it matters: Measuring on the target device is safer than assuming a simple conditional has negligible cost. - Grouped enemy status arrays: Explain how separating alive and dead enemy indices removes status checks from the enemy loop, and state the resulting bookkeeping trade-off.
Why it matters: This shows how a data-layout choice can simplify a frequently run loop while shifting work to bookkeeping.
Key terms: branches, code complexity, branch prediction, branch misprediction, pipeline, comparison and jump instructions, data-oriented design, alive and dead enemy indices, arrays, branch checks
11.1 Branch prediction
This section uses a controlled comparison to show that predictable branch results are easier for a CPU to predict than random ones.
- Branch result predictability: Explain that a predictable pattern of branch results makes it easier for branch prediction to guess which branch will be taken than random results do.
Why it matters: The comparison shows why the pattern of branch outcomes can matter to performance. - Controlled branch comparison: Describe how the test compares alternating and random branch results while keeping the work done for either result the same.
Why it matters: Keeping the work the same makes the branch results, rather than different workloads, the point of comparison.
Key terms: branch prediction, predictable branch results, branch misprediction, Array, Mod2Array, RandomArray
11.2 Avoiding early return
The section explains why moving branches and repeated validation out of a hot function makes its behavior clearer and avoids unnecessary checks.
- Branch outside enemy movement: Explain why the paralysis check should sit outside moveEnemy() rather than make moveEnemy() sometimes return without moving an enemy.
Why it matters: A reliable function name makes movement code easier to follow when debugging. - Validation at system boundaries: Distinguish useful validation at system edges from repeated early-return checks in controlled runtime code, and explain how to respond if supposedly valid data proves invalid.
Why it matters: Checking assumptions in the right place keeps hot code simple without ignoring invalid input or concealing bugs.
Key terms: moveEnemy(), branch, paralyzed, early-return branch checks, edges of the system, controlled runtime loop, hot code
11.3 Unity and null checks
Explains why Unity object null checks differ from ordinary C# checks, why some C# null syntax is unsafe for them, and how much repeated checks can cost.
- Unity object null semantics: Explain why checking a GameObject or MonoBehaviour for null involves more than checking an ordinary C# reference.
Why it matters: A Unity object can have a C# wrapper even when the native object it represents no longer exists. - C# null syntax risk: Distinguish Unity's overloaded null comparison from C# null syntax such as ?. and ?? when used with GameObjects or MonoBehaviours.
Why it matters: A check that sees the surviving wrapper may give the wrong impression about whether the Unity object still exists. - Runtime null-check cost: Describe the section's comparison of GameObject access with and without a null check and its performance result.
Why it matters: Repeating Unity object null checks in hot runtime loops can cost noticeably more than an ordinary branch.
Key terms: UnityEngine.Object, managed reference, native object, equality operator, null-conditional operator, null-coalescing operator, == null, null check, GameObject, Android
11.3.1 Check once
This subsection explains how to avoid repeated Unity null checks for asset references while recognizing that objects can still be destroyed unexpectedly.
- One-time asset reference checks: Explain why references assigned in the Unity Editor need not be checked for null throughout gameplay, and describe when to check downloaded assets instead.
Why it matters: Moving checks out of gameplay avoids paying for repeated null checks when a reference is assigned only once. - Dynamic asset readiness flag: Describe the suggested way to avoid repeated Unity-object null checks when assets download dynamically as the player accesses new areas or features.
Why it matters: A readiness flag lets gameplay track whether a dynamically loaded object is available without repeatedly checking the Unity object for null. - Unexpected object destruction risk: Describe how a Unity object can be destroyed unexpectedly and what can happen when other code continues using it.
Why it matters: Checking a reference once does not prevent crashes if the object is later destroyed while other code still uses it.
Key terms: AssetManager, null check, #if UNITY_EDITOR, dynamically download assets, separate boolean, Unity object, GameObject, parent object, coroutines, asynchronous calls
11.3.2 Zero Tolerance
This section explains why Unity teams should treat development errors as stop-work events and how to make logged errors hard to miss.
- Zero tolerance for development errors: Explain why an error should stop play during development rather than remain a console message that the team can ignore.
Why it matters: Stopping on errors makes it harder to miss a problem while the game appears playable. - Unity error interception: Describe the Unity approach given for detecting errors and making them visible enough to halt development play.
Why it matters: This turns the zero-tolerance policy into an action the Unity development team can notice.
Key terms: zero-tolerance approach, null reference, console errors, logMessageReceived, error, exception, editor
11.3.3 Own the lifetime
Owning GameObject lifetimes makes their validity predictable, allowing unnecessary runtime null checks to be removed.
- Owned GameObject lifetimes: Explain why controlling when GameObjects are created and deallocated can make null checks unnecessary, including for dynamically instantiated objects. Describe how avoiding those checks helps performance, readability, and debugging.
Why it matters: Predictable object lifetimes let you remove checks without guessing whether an object still exists.
Key terms: GameObjects, lifetime, null checks, Init(), Tick(), dynamic pool
11.3.4 Avoid fire-and-forget behavior
This section explains how work that outlives a Unity GameObject causes hard-to-find errors and why explicitly controlled ticking is safer for the book’s frame-by-frame gameplay systems.
- Callbacks outliving GameObjects: Explain how a coroutine or static event callback can still reference a GameObject after it is destroyed, even though Unity often stops coroutines owned by the destroyed object.
Why it matters: It identifies the lifetime mismatch behind errors that may appear only during quick menu or scene transitions. - Explicit control of ticking: Justify using owned timers and a Tick() function instead of fire-and-forget behavior in the book’s frame-by-frame gameplay systems, and describe what happens when a system is no longer active.
Why it matters: Stopping a system’s updates addresses the lifetime problem rather than waiting for an abandoned callback to encounter a destroyed target.
Key terms: coroutine, static event subscriptions, GameObject, MonoBehaviour, fire-and-forget behavior, timers, Tick(), null checks
11.4 Separating data to reduce branch checks
The section shows how storing indices by their branch result reduces checks when iterating enemies and finding unused GameObjects in a pool.
- Data separated by branch result: Explain how separate index arrays reduce branch checks, using alive and dead enemies as the example.
Why it matters: Grouping data by the result you need can remove repeated checks from a loop. - Unused pool index search: Describe how an array of unused pool indices changes the search for a free GameObject, including what happens when none are available.
Why it matters: Tracking unused entries narrows the search without claiming to eliminate every branch. - Unused index lifecycle: Trace how the Board initializes, adds to, and resets its unused pool indices.
Why it matters: The shorter search works only if the unused-index array reflects which pool objects have been released.
Key terms: branch checks, aliveEnemyIndices, deadEnemyIndices, isAlive, GameObject pool, m_enemyPoolUnusedIndices, m_enemyPoolUnusedIndicesCount, m_enemyPoolUsed, Show(), Board.Tick()
11.5 Separating objects to avoid branch checks
The section argues for separate UI scripts when menus need different behavior, while preserving visual consistency through shared assets and data.
- Distinct scripts for menu variants: Explain why the settings, in-game, and game-over top bars should use separate scripts rather than one TopBar script full of branches.
Why it matters: A shared-looking UI element does not necessarily need one shared script. - Isolated fixes and shared styling: Describe how separate menu scripts limit the effects of fixes and QA retesting, while shared assets and data keep the UI visually consistent.
Why it matters: This keeps menu changes contained without giving up a consistent visual style.
Key terms: top bar, branches, data-oriented design, shared assets, shared data, QA, MainMenuTopBar
11.6 Default parameter values can hide branches
This section shows how a default parameter can make a branch inside a method easy to overlook at its call sites.
- Hidden branches from default parameters: Explain how a default value for moveEnemy()’s enemyParalyzed boolean lets existing calls omit the argument while concealing a branch, and why changing that default could break those calls.
Why it matters: A convenient default can make branching behavior and the consequences of changing it less visible to callers.
Key terms: default parameter values, moveEnemy(), enemyParalyzed, hidden branch
11.7 Conclusion
The conclusion connects the performance and readability costs of branches to ways of reducing checks in Unity code.
- Branch costs and hidden checks: Explain why branches can hurt performance and readability, and identify default parameter values as a possible source of hidden branch checks.
Why it matters: A branch can impose a cost even when it looks harmless or is not obvious in the code. - Unity GameObject null checks: Explain why repeated GameObject null checks cost extra work in Unity and describe the approaches given for limiting them safely.
Why it matters: Controlling when objects are validated and destroyed can avoid costly repeated checks without ignoring missing objects. - Separation instead of repeated branching: Describe how separating enemy and pool data, and splitting shared UI elements, avoids checks and limits the effects of changes.
Why it matters: Organizing data and UI around their distinct uses can remove checks while making features easier to change independently.
Key terms: branches, branch prediction, default parameter values, GameObjects, null checks, overloaded equality operator, zero-tolerance policy, fire-and-forget behavior, alive and dead enemies, unused pool object indices
11.8 Summary
The summary explains why branches can hurt performance and maintainability, and how managing object lifetimes and separating data can reduce repeated checks.
Concepts explained in this chapter
- branchControl flow that selects among different execution paths, commonly according to conditions.
- complexity metricA measure of the structural intricacy and difficulty of understanding, modifying, or executing software code.
- null handlingA null check is a test that determines whether a reference or object represents no value or has been invalidated.
- branch predictionBranch prediction is processor hardware behavior that predicts the outcome of a conditional branch before it is resolved.
- branch mispredictionA branch misprediction is an incorrect processor prediction of the outcome or execution path of a conditional branch.
- early returnAn early return is a control-flow technique in which a function exits before reaching its normal completion point.
- data-oriented programmingAn approach to structuring software around the flow and transformation of data rather than relationships between objects.
- validationThe process of checking data or references against validity constraints before use.
- arrayAn indexed sequence of elements, typically stored in contiguous memory.
- extensibilityThe property of software that allows new capabilities or content to be added with limited changes to existing code.
These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.
