r/cpp • • 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.

81 Upvotes

79 comments sorted by

View all comments

Show parent comment

1

u/pigeon768 May 22 '26

It amazes me that people think holding on to old dependencies for years is fine. Bumping a dependency version every six months or so is relatively easy. Bumping a dependency 5 years is bound to cause one or more things to break catastrophically, and since numerous things are catastrophically broken, it's very difficult to determine which individual fixes are actually giving you forward progress.

Sitting down and writing new code based on a 5 year old dependency is especially ridiculous.

On the one hand, I don't know how people create working software like this. On the other hand, it's a stretch to call most people's software "working".

2

u/archialone May 23 '26

Yeah. I find it funny when organization spend enormous amount of effort coding around issues or limitations of old dependancies, instead of spending same amount of time and effort upgrading them.

And it ends up even less effort to upgrade.