r/cpp • u/AdMotor4869 • May 19 '26
Virtual dispatch isn't always the slowest, and std::variant isn't always the fastest
https://shubhankar-gambhir.github.io/posts/four-ways-to-dispatch-a-runtime-selected-strategy-in-cpp/I've been looking at how OpenJDK's GC barrier system picks its implementation at runtime using templates instead of virtual dispatch. The trick is lazy resolution: you pay once at first use instead of a vtable lookup on every call.
That got me curious enough to benchmark it against three other approaches: virtual functions, function pointers, and std::variant + std::visit. I was surprised to see std::variant being the slowest on libstdc++ while virtual dispatch beat it comfortably.
Please refer to the blog for my full analysis. Would love to hear what you think!
Edit: Benchmarks are on GCC 11 (Ubuntu 22.04 default). GCC 12+ significantly improves std::visit. Full compiler version comparison in the next post.
View all comments
Show parent comment
1
u/f0r3v3rn00b May 22 '26 edited May 22 '26
There's a big misunderstanding as well when it comes to the benefit of avoiding virtual functions.
99% of the time, it's not about direct calls (static function, known address) vs dynamic calls (dynamic dispatch aka indirect jump), it's about the ability for the compiler to inline function calls. So it's about calling a function vs not calling it because it's been inlined.
When you have a nice set of abstractions, with small functions like setters, getters, proxies, visitors, generally small functions that call other small functions, CRTP will be much faster than virtual functions, because CRTP allows the compiler to inline and dissolve abstractions and small functions into a few instructions, sometimes only 1 instruction. With virtual functions, the compiler will very rarely be able to do the same (Yeah I know devirtualization exists, but it's rarely possible outside of toy examples), and your code ends up spending 70% of the runtime doing stack management, register restoration, __security_check_cookie and such...
Now, this is irrelevant if a virtual function does a significant amount of work (I'd say at least a hundred of CPU instructions). But I've seen code bases where there are lots of one-liner virtual functions such as
size,visit,unwrapand such. Those kind of code bases tend to end up with java-like performances. Every object having to be heap-allocated also doesn't help. I've seen a ray-tracing heavily abstracted implementation get a x10 speedup by using CRTP instead of virtual functions. Almost like debug vs release. It was because it went from "nothing is inlined" to 90% of function calls inlined.