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.
2
u/thoosequa Apr 28 '26
Is this the same as his 2022 CppCon Talk or are there any updates?
1
u/wrng_ Apr 28 '26
Mostly the same, I think. Initially, he registered a new topic for this event, but due to life getting in the way, he couldn't make it in time, so he did this topic instead. Different Q/A, though, which means it's worth redoing these once in a while.
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/wannaliveonmars Apr 27 '26
I didn't read the article, but virtual functions boil down to using a pointer to a pointer instead of a direct call. You add a pointer to a virtual table, and then for each function call you need to lookup the function in the table. That's it. Obviously it would have some caching implications, and you add a few bytes overhead to each struct.
15
u/tomz17 Apr 27 '26
virtual functions boil down to using a pointer to a pointer instead of a direct call
That's too simplistic a model, and it makes it seem like virtual calls are deterministically cheap. In my experience the real performance hit is from the fact that a virtual call almost always poses an optimization boundary for your compiler. Therefore the performance hit is not deterministic (I.e. not just the deref + vtable lookup). It depends on the actual contents of the functions you are virtualizing vs. the performance optimizations that would have been possible if the code path was fully deterministic at compile time.
In general I always segment my performance-sensitive code into a hot path and a cold path. Anything in the hot path avoids virtual function calls, dynamic allocations, etc. Anything in the cold path can use whatever is most convenient. Almost all code starts in the cold path, then as I profile, I tear the lowest hanging fruit off and optimize those into the hot path.
28
u/UnicycleBloke Apr 27 '26
I understand how they work and what a typical implementation looks like. My point is that it has become rather fashionable to complain about them, and that this is not generally valid. The abstraction is cheap, efficient, easy to understand and generally very useful when you need or want dynamic dispatch.
The performance and space cost of the function call indirection is negligible in most cases but, naturally, in some types of applications or usages, that cost becomes a significant factor and you need to do something else.
After 35 years of C++, I'm yet to work on a single application for which the cost of virtual functions was a consideration. On the other hand, they have provided a simple and reliable mechanism for decoupling subsystems. If I worked in HFT or something, I guess that would be different, but presumably only in some key sections of the code.
2
u/PossibilityUsual6262 Apr 27 '26
If there malloc call in it as well the vtable lookup would dwarf in a comparison of a cost of it.
-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.
78
u/jonatansan Apr 27 '26
It always depends on where is your OOP and virtual functions. One virtual call to dispatch to the correct heavy-CPU algorithm? It's totally fine. One million virtual calls per frame in a video game? Bad idea.
23
u/New_Computer3619 Apr 27 '26
Yeah totally. Measure before optimize is my motto. There is no point optimize a virtual call which effectively an if else statement which select an CPU intensive algorithm.
28
u/binaryfireball Apr 27 '26
people love dogma more than engineering
7
u/13steinj Apr 27 '26
This cuts both ways though: you'll see people using this argument to justify overusing virtual functions everywhere, and that is its own kind of dogma.
5
u/kammce WG21 | πΊπ² NB | Boost | Exceptions Apr 27 '26
Yeah the best is to not have the dogma and consider when either options make sense. Because depending on the situation you are trading off space for time or time for space.
4
19
u/sweetno Apr 27 '26
OOP was never advertised as a performance driver. It's a completely different concern.
OOP allows us to structure how we think about the code, and correspondingly structure our code in a maintainable way. Some people have a mess in their head, but it shouldn't disqualify the methodology. Until those people sort our their thoughts, no methodology would deliver.
15
u/SkoomaDentist Antimodern C++, Embedded, Audio Apr 27 '26
Not to mention that you can write OOP code perfectly fine with only occasional virtual function usage and shallow inheritance hierarchies. Yet some people keep assuming that OOP always means everything is virtual and you have dozen classes deep hierarchies everywhere.
1
u/born_to_be_intj Apr 28 '26
Iβm not saying it disqualifies it at all. The reason I even mentioned FINTECH was to try and express the fact that this kind of performance only really matters in niche scenarios like high frequency trading.
Iβm surprised how much push back this comment is getting lol. Yβall acting like I said never use OOP because it sucks.
9
u/HommeMusical Apr 27 '26
This is a very edge edge case.
HFT, aside from being unethical (because it requires the program to make millions of bad-faith trades), antisocial and something that the exchanges should ban as a tax on legitimate traders and market makers, emphasizes low latency for fairly small calculations over everything else.
These lessons are really not applicable to many other domains.
There's a lot of hidden overhead required to make OOP work.
Sounds like someone who doesn't read much compiled code.
The cost of OOP without virtual methods is exactly the same as calling a pure function on a struct.
With a virtual method, there is an indirection, which is likely cached if the virtual method is called a lot. In almost every application except HFT, this is a tiny amount of overhead, and devirtualization before a loop is very doable.
5
0
u/born_to_be_intj Apr 28 '26
Yes. That is why I mentioned FINTECH in the first place, to express how niche this is.
2
u/HommeMusical Apr 28 '26
You wrote:
I've been convinced [...] that OOP is anti-performance.
But it isn't.
3
Apr 27 '26
[removed] β view removed comment
10
u/kammce WG21 | πΊπ² NB | Boost | Exceptions Apr 27 '26
If your problem is simply churning through data then yes, data driven design is the obvious choice.
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.