C++ Performance Tips - Cutting Down on Unnecessary Objects
summary
Extra temporaries cost CPU and heap: examples show a copy of std::string or std::vector causing two heap allocations vs one when moved or constructed in place, and range-for with plain auto producing two copies for a two-element vector. Practical fixes include passing non‑trivial readonly objects by const reference, using std::string_view and std::span to avoid conversions, reserving and using reserve + emplace_back for vectors, preferring in‑place constructors (emplace, piecewise_construct), and enabling diagnostics like -Wall and clang‑tidy performance checks.
AI-written summary · about
chapters (39)
- 0:00Introduction
- 1:07Unnecessary objects hurt performance
- 3:14Costly object creation
- 6:01When extra objects are acceptable
- 7:24Detecting unnecessary objects
- 8:07Avoid temporary function args
- 9:52Efficient return non-trivial members
- 11:59Range-based loops and copies
- 13:22Structured bindings and copies
- 14:04Named return value optimization pitfalls
- 16:57Lambda captures and references
- 18:57Capturing variadic arguments by reference
- 19:39String view to avoid temps
- 21:30Move parameters to avoid copies
- 21:52String concatenation with reserve
- 23:18String view substr savings
- 23:59Reserve vector capacity
- 25:03Use span instead of vectors
- 26:08Initializer lists and temps
- 27:09Pair construction and move
- 27:51Tuple construction alternatives
- 28:57Optional in-place construction
- 29:59Expected error handling
- 31:44Variant in-place changes
- 33:50Two array vs array
- 34:33emplace_back vs push_back
- 36:18emplace for map keys
- 37:22emplace for map values
- 38:29emplace vs try_emplace
- 39:13emplace with pair constructors
- 40:16insert_or_assign for maps
- 41:39Transparent comparators
- 44:47Transparent comparators unordered
- 46:52Moving data to compile time
- 47:56Magic statics and exit destructors
- 48:38Compile-time data structures
- 49:40Compile-time string concatenation
- 50:26Compile-time sets/maps limits
- 50:47Key takeaways and final recommendations
related talks
44mC++ Performance and Optimisation
01h 00mMoving Faster: Everyday efficiency in modern C++
01h 01mRecipes for Reducing Allocations by C++ Containers
51mTypical C++, but Why?
57mSome Things C++ Does Right
01h 03mC++ Trivial Relocation Through Time
01h 00mThe Fine Details Behind C++ Containers And Algorithms
01h 31mNew (& Old) C++ Standard Library Containers - How to Choose the Right Container in C++26 and Beyond
