C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Fwd: Extension to runtime polymorphism proposed

From: Thiago Macieira <thiago_at_[hidden]>
Date: Wed, 01 Apr 2026 22:53:50 -0700
On Wednesday, 1 April 2026 21:56:44 Pacific Daylight Time Muneem via Std-
Proposals wrote:
> /*
> Time (ns) for switch: 168100
> Time (ns) for visit: 3664100
> Time (ns) for ternary: 190900
> It keeps on getting worse!
> */

So far you've maybe shown that one implementation is generating bad code. Have
you tried others?

You need to prove that this is an inherent and unavoidable problem of the
requirements, not that it just happened to be bad for this implementation.
Just quickly reading the proposed benchmark code, it would seem there's no
such inherent reason and you're making an unfounded and probably incorrect
assumption about how things actually work.

In fact, I pasted a portion of your code into godbolt just to see what the
variant visit code, which you claim to be unnecessarily slow, would look like:
https://gcc.godbolt.org/z/WK5bMzcae

The first thing to note in the GCC/libstdc++ pane is that it does not use
user_index. The compiler thinks it's a constant, meaning this benchmark is
faulty. And thus it has constant-propagated this value and is *incredibly*
efficient in doing nothing useful. MSVC did likewise.

Since MSVC outputs the out-of-line copy of inlined functions, we can see the
operator() expansion without the proapagation of the user_index constant. And
it's no different than what a ternary or switch would look like.

In the Clang/libc++ pane, we see indirect function calls. I don't know why
libc++ std::variant is implemented this way, but it could be why it is slow
for you if you're using this implementation. If you tell Clang to instead use
libstdc++ (remove the last argument of the command-line), the indirect
function call disappears and we see an unrolled loop of loading the value 10.
That would mean Clang is even more efficient at doing nothing.

Conclusion: it looks like your assumption that there is a problem to be solved
is faulty. There is no problem.

-- 
Thiago Macieira - thiago (AT) macieira.info - thiago (AT) kde.org
  Principal Engineer - Intel Data Center - Platform & Sys. Eng.

Received on 2026-04-02 05:53:58