Optimizing Away C++ Virtual Functions May Be Pointless
summary
Benchmarks show surprising, inconsistent numbers: 2% faster 42% faster 54% faster on one run and 78% slower 14% slower 35% slower 18% slower on another. Real use case: a preprocessing step that serializes different formats, measured with a virtual-base-class runtime dispatch and a template-expanded compile-time dispatch. Results vary by CPU (Intel vs AMD), compiler (GCC vs Clang), and cache effects; std::variant/std::visit often fares worst and can deoptimize to indirect calls. Conclusion: measure the actual code+hardware+flags, don’t assume virtuals are inherently slower.
AI-written summary · about
chapters (11)
- 0:00Virtual function myths
- 1:10Inheritance and virtual functions
- 3:44Benchmarking virtual functions
- 5:51Misleading benchmarks
- 7:57Serialization benchmark
- 10:06Hardware and compiler impact
- 12:13Cache behavior analysis
- 17:32Performance variability
- 20:42Virtual function importance
- 23:38Design philosophy
- 26:57Q&A
related talks
49mThe Hidden Performance Price of C++ Virtual Functions
01h 00mIntroduction to Hardware Efficiency in Cpp
01h 01mUsing Modern C++ to Eliminate Virtual Functions
01h 05mThe Most Important Optimizations to Apply in Your C++ Programs
01h 03mHidden Overhead of a Function API
01h 00mC++ MythBusters
01h 01mWant fast C++? Know your hardware!
44mCompilation Speedup Using C++ Modules: A Case Study
