C++ Compiler Optimization

8 min

Discover how compilers optimize your C++ code through various transformation techniques with interactive demos.

Best viewed on desktop for optimal interactive experience

Compiler Optimization Techniques

Modern compilers transform your code through multiple optimization passes to improve performance and reduce size. See these transformations in action:

Compiler Optimization Passes

Optimization Level

Active passes: constant-folding, dead-code, inline-expansion, cse

Constant Folding

Evaluate constant expressions at compile time

Before Optimization

int calculate() {
    int a = 2 * 3;
    int b = 10 / 2;
    int c = a + b;
    return c * 4;
}

After Optimization

int calculate() {
    return 44;
    // 2*3=6, 10/2=5
    // 6+5=11, 11*4=44
}

Transformation Steps

1
Originalint a = 2 * 3;
Transformedint a = 6;
ReasonFold 2 * 3 = 6
2
Originalint b = 10 / 2;
Transformedint b = 5;
ReasonFold 10 / 2 = 5
3
Originalint c = a + b;
Transformedint c = 11;
ReasonFold 6 + 5 = 11
4
Originalreturn c * 4;
Transformedreturn 44;
ReasonFold 11 * 4 = 44
Speed Gain
+10-25%
Code Size
~0%
Compile Time
+20-40%
Best For
Math Heavy

Optimization Levels

-O0: No Optimization

  • Fastest compilation
  • Best for debugging
  • Code matches source closely

-O1: Basic Optimization

  • Simple optimizations
  • Reasonable compile time
  • Better performance
  • Most optimizations enabled
  • Good balance
  • Standard for release builds

-O3: Aggressive

  • All -O2 plus aggressive inlining
  • Larger binary size
  • May not always be faster

-Os: Size Optimization

  • Optimize for code size
  • Good for embedded systems
  • Some performance trade-offs

Common Optimizations

Constant Folding

// Before int x = 2 * 3 + 4; // After int x = 10;

Dead Code Elimination

// Before if (false) { expensive_function(); } // After: removed entirely

Loop Unrolling

// Before for(int i = 0; i < 4; i++) sum += arr[i]; // After sum += arr[0]; sum += arr[1]; sum += arr[2]; sum += arr[3];

Function Inlining

// Before inline int square(int x) { return x*x; } int y = square(5); // After int y = 25;

Optimization Hints

// Likely/Unlikely branches (C++20) if ([[likely]] condition) { } // Force inline __attribute__((always_inline)) inline void fast_function() { } // Prevent optimization __attribute__((optimize("O0"))) void debug_function() { }

Performance Impact

OptimizationSpeed GainSize Impact
Constant Folding5-15%Reduced
Inlining5-20%Increased
Loop Unrolling10-30%Increased
Dead Code5-10%Reduced

Next Steps

If you found this explanation helpful, consider sharing it with others.

Mastodon