Skip to content

Performance_basics

This chapter covers essential techniques for writing high-performance C++ code.

┌─────────────────────────────────────────────────────────────┐
│ Rule of Optimization │
├─────────────────────────────────────────────────────────────┤
│ │
│ 1. Don't optimize prematurely │
│ 2. Profile first to find bottlenecks │
│ 3. Measure after optimization │
│ 4. Focus on the critical path │
│ │
└─────────────────────────────────────────────────────────────┘
// Allows compiler optimizations
void process(const std::vector<int>& data);
// Bad: Copy
void process(std::vector<int> v);
// Good: Reference
void process(const std::vector<int>& v);
std::vector<int> v;
v.reserve(1000); // Pre-allocate
// Bad
auto copy = original;
// Good
auto& ref = original;
inline int square(int x) { return x * x; }
// Bad: Heap allocation
int* arr = new int[100];
// Good: Stack allocation
int arr[100];
  • gprof: GNU profiler
  • Valgrind: Memory profiler
  • perf: Linux performance analyzer
  • Visual Studio Profiler: Windows
Terminal window
# Basic optimization
g++ -O2 program.cpp -o program
# Aggressive optimization
g++ -O3 program.cpp -o program
# Optimize for size
g++ -Os program.cpp -o program
  • Profile before optimizing
  • Focus on algorithmic improvements first
  • Use compiler optimizations
  • Prefer stack over heap when possible
  • Use const and references appropriately