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
0
u/zerhud May 20 '26
There is a benchmark results in swl readme: 250 for if chain vs 5 on switch-case.
Branch prediction works on few ifs, not for few hundred ifs. But it’s true: if your variant has only few cases it doesn’t matter. Also branch prediction works if execution path repeated.
I’ve tried to use it with parser, so the variant contains near about 300 variants, and it takes veeeery much time to compiles, the binary size is huge and works slowly, but my variant implementation (also with switch case, and I’ve tried also a table of functions pointers) was a way better.
UPD: wrong data copied