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
Original
int a = 2 * 3;Transformed
int a = 6;ReasonFold 2 * 3 = 6
2
Original
int b = 10 / 2;Transformed
int b = 5;ReasonFold 10 / 2 = 5
3
Original
int c = a + b;Transformed
int c = 11;ReasonFold 6 + 5 = 11
4
Original
return c * 4;Transformed
return 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
-O2: Recommended
- 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
| Optimization | Speed Gain | Size Impact |
|---|---|---|
| Constant Folding | 5-15% | Reduced |
| Inlining | 5-20% | Increased |
| Loop Unrolling | 10-30% | Increased |
| Dead Code | 5-10% | Reduced |
Next Steps
- Explore Object Files & Symbols
- Learn about Linking Process
- Master Memory Layout
