The Hidden Performance Price of C++ Virtual Functions
https://www.youtube.com/watch?v=3ux5YEj1c54At the online weekend series by Global C++, Ivica from https://johnnysswlab.com/ explains, with examples, what the actual cost of using virtual functions in current C++ with modern hardware actually is.
61
Upvotes
23
u/kammce WG21 | πΊπ² NB | Boost | Exceptions Apr 27 '26
I got to 8:00 and decided to comment. I appreciate that the initial analysis had a discussion about function complexity and time. For example, when working with IO, where the IO is orders of magnitude longer than a virtual dispatch, it's not very important to get those few nanoseconds back.
But where I was lost was on the slide where it is claimed that virtual dispatch REQUIRES dynamic memory allocation. This is false. You can have objects that are automatic (on the stack) or statically allocated. Repeating this falsehood has resulted in many misunderstandings and myths about the utility of virtual APIs in C++. We should stop repeating this.
2
u/thoosequa Apr 28 '26
Is this the same as his 2022 CppCon Talk or are there any updates?
43
u/UnicycleBloke Apr 27 '26
A great deal depends on context. What does the function do? How frequently is it called? Does your device even have a cache? Are you using a memory pool for dynamic allocations? Are the objects even allocated dynamically? In most applications, the cost of a virtual call is lost in the noise. Virtual functions are a sensible and efficient solution to a number of design problems. Of course, they are not necessarily the most appropriate tool for every design problem.
-4
u/born_to_be_intj Apr 27 '26
I've been convinced by a FINTECH guy who writes extremely performant C++ code that OOP is anti-performance. There's a lot of hidden overhead required to make OOP work.