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

21

u/AdMotor4869 May 19 '26

It's more about how libstdc++ implements std::visit than what the compiler can optimize. The compiler does its job fine, but it can't optimize away a exception check that the library explicitly puts there. libc++ makes different implementation choices and the same code runs faster.

6

u/QuaternionsRoll May 19 '26

Sorry, what exception check is that? Do you mean the valueless_by_exception -> throw std::bad_variant_access() path?

If so, that’s not exactly a required feature, and I’m curious if a custom tagged union implementation would fare better.

7

u/AdMotor4869 May 20 '26

Yes, the valueless_by_exception check. Though for trivially copyable types libstdc++ actually elides it since GCC 9, so it's not the main overhead here. The bigger cost was the lambda capture round-trip. GCC 12+ replaces the function pointer table with a switch which fixes this.