Technology
How GCC chooses between jump tables, bitsets and comparison trees
GCC lowers switch statements through several strategies, including jump tables, bit tests and comparison trees. This technical explainer shows how case density, contiguous ranges, duplicate targets, branch probabilities, architecture-specific thresholds and optimization-for-size versus optimization-for-speed affect those choices. It also describes the compiler’s dynamic-programming passes for clustering cases and explains why apparently simple heuristics depend on comparison counts and dispatch overhead. The examples are useful for understanding generated machine code and compiler profitability decisions.
Editorial summary · Publisher article
What matters
- Dense case ranges can become jump tables, while sparse cases often become comparison trees.
- GCC can use bit tests when case labels fit an efficient bitset representation.
- Contiguous labels sharing a target can reduce the number of comparisons needed.
- Optimization for speed uses a looser jump-table ratio than optimization for code size.
Profitability drives the transformation
GCC weighs table size, the number of comparisons, dispatch overhead, case-label density and architecture-dependent thresholds before choosing a lowering strategy.
Profile information shapes decision trees
When bitsets or jump tables are not worthwhile, GCC uses case probabilities to divide a comparison tree so likely paths can be reached efficiently.
Context & caveats
- The article focuses on GCC behavior and examples; generated code can vary with target architecture, compiler version and optimization settings.
Why this made the edition
A complete, technically detailed explainer uses concrete compiler output and source-level reasoning to explain GCC’s switch-lowering strategies, heuristics and tradeoffs.
Source material