Performance_basics
Performance Optimization Basics
Section titled “Performance Optimization Basics”This chapter covers essential techniques for writing high-performance C++ code.
Rule of Optimization
Section titled “Rule of Optimization”┌─────────────────────────────────────────────────────────────┐│ Rule of Optimization │├─────────────────────────────────────────────────────────────┤│ ││ 1. Don't optimize prematurely ││ 2. Profile first to find bottlenecks ││ 3. Measure after optimization ││ 4. Focus on the critical path ││ │└─────────────────────────────────────────────────────────────┘Common Optimizations
Section titled “Common Optimizations”1. Use const Correctly
Section titled “1. Use const Correctly”// Allows compiler optimizationsvoid process(const std::vector<int>& data);2. Pass by Reference
Section titled “2. Pass by Reference”// Bad: Copyvoid process(std::vector<int> v);
// Good: Referencevoid process(const std::vector<int>& v);3. Use Reserve for Vectors
Section titled “3. Use Reserve for Vectors”std::vector<int> v;v.reserve(1000); // Pre-allocate4. Avoid Unnecessary Copies
Section titled “4. Avoid Unnecessary Copies”// Badauto copy = original;
// Goodauto& ref = original;5. Use Inline Functions
Section titled “5. Use Inline Functions”inline int square(int x) { return x * x; }6. Prefer Stack over Heap
Section titled “6. Prefer Stack over Heap”// Bad: Heap allocationint* arr = new int[100];
// Good: Stack allocationint arr[100];Profiling Tools
Section titled “Profiling Tools”- gprof: GNU profiler
- Valgrind: Memory profiler
- perf: Linux performance analyzer
- Visual Studio Profiler: Windows
Compiler Optimizations
Section titled “Compiler Optimizations”# Basic optimizationg++ -O2 program.cpp -o program
# Aggressive optimizationg++ -O3 program.cpp -o program
# Optimize for sizeg++ -Os program.cpp -o programKey Takeaways
Section titled “Key Takeaways”- Profile before optimizing
- Focus on algorithmic improvements first
- Use compiler optimizations
- Prefer stack over heap when possible
- Use const and references appropriately