---
name: cpp-performance-optimization
description: "Techniques for optimizing C++ performance, from cache-friendly algorithms to compiler flags."
language: cpp
---

# C++ Performance Optimization

Strategies for making C++ applications as fast and efficient as possible.

## Guidelines
- **Prefer Cache-Friendly Data Structures**: Use `std::vector` (contiguous memory) over `std::list` (linked nodes) for better CPU cache locality.
- **Minimize Memory Allocations**: Reuse buffers, use `std::string_view` to avoid copies, and prefer stack allocation for small objects.
- **Inlining**: Use `inline` for small, frequently called functions, but trust the compiler's heuristics for larger functions.
- **Avoid Unnecessary Virtual Calls**: Virtual functions have a small overhead; avoid them in performance-critical inner loops if possible.
- **Optimize Compiler Flags**: Use `-O3`, `-march=native`, and Link-Time Optimization (LTO).
- **Move Semantics**: Use `std::move` and implement move constructors/assignment operators to avoid expensive copies.
- **Profile with Tools**: Use `perf`, `Valgrind (Callgrind)`, or `VTune` to identify real bottlenecks.

## Tools & Libraries
- **perf**: Linux profiling tool for CPU performance.
- **Valgrind (Callgrind/Massif)**: For profiling and memory analysis.
- **Google Benchmark**: Library for micro-benchmarking C++ code.
- **Intel VTune Profiler**: Deep performance analysis for Intel processors.

## Trigger Scenarios
- When an application is running slower than expected or missing latency targets.
- When optimizing hot loops or data-intensive algorithms.
- When reducing memory bandwidth usage or CPU cycles.
- When a developer asks how to leverage modern C++ features for performance.

<!-- synapsis-dsai-managed -->
