CcCompilers · Lesson 5 of 7
Optimization — Where the Magic Lives
Naively translated code is slow. Optimizers transform the program — hundreds of passes, each a small rewrite that provably preserves behavior — until the output beats what you'd write by hand.
The contract is the 'as-if' rule: the optimizer may do anything as long as observable behavior is unchanged. This is also where undefined behavior gets teeth — in C, signed overflow is UB, so the compiler assumes it never happens and deletes your 'if (x + 1 < x)' overflow check as dead code. The optimizer isn't malicious; it's holding you to the language's rules.
✦ Tip
Practical takeaways: write clear code — the optimizer handles micro-tricks better than you, and clear code optimizes better. Debug builds (-O0) are slow on purpose (variables stay in memory so debuggers can see them). And when a benchmark shows 0ns, the optimizer probably deleted your unused computation entirely.
Practical takeaways: write clear code — the optimizer handles micro-tricks better than you, and clear code optimizes better. Debug builds (-O0) are slow on purpose (variables stay in memory so debuggers can see them). And when a benchmark shows 0ns, the optimizer probably deleted your unused computation entirely.