IT lexicon › Programming › Loop unswitching

Loop unswitching

Programming På svenska → Updated: 2026-11-05

A condition inside a loop that never changes during the loop is hoisted out, and the loop is duplicated into one version per outcome.

A loop that asks if (debug) on every iteration pays for the question millions of times even though the answer was settled before it started. The compiler can instead test the condition once and jump to one of two copies of the loop, each with the branch removed. It's a relative of loop-invariant code motion, except what gets moved is control flow rather than a computation.

The price is code size: every hoisted condition doubles the loop, so three conditions mean eight copies, and compilers cap how far they'll go. GCC does it with -funswitch-loops, which is on at -O3 but not -O2, and LLVM has its own pass for the same job. The branch-free copies are also much easier to vectorise.

← Back to the lexicon