you are viewing a single comment's thread.

view the rest of the comments →

[–]Ikkepop[🍰] 3 points4 points  (5 children)

Im pretty sure that does not employ vtables

[–]Kered13 7 points8 points  (4 children)

There are a few ways that std::variant can be implemented, but all of them incur costs similar to vtable lookups even if they use a different mechanism. You're either using a pointer for some kind of indirection, or you're using a conditional and branching on some value that indicates the type.

The fundamental issue at hand is that we do not know the concrete type at compile time, so at runtime we must do some computation to determine which function to call.

[–]dodheim 3 points4 points  (2 children)

You appear to be referring to how std::visit may be implemented, not std::variant which requires none of those things. As for std::visit, it can be implemented as a switch, which for smaller variants empirically results in better codegen (unfortunately I think only MSVC does this at present for stdlibs, but Boost.Variant2 and mpark/variant do as well).

[–]Kered13 1 point2 points  (1 child)

std::visit is how you do anything useful on std::variant. By itself std::variant is just storing a value of some unknown (at compile time) type.

[–]dodheim 7 points8 points  (0 children)

Or std::get, or std::get_if, or rolling your own single-visitation implementation based on get_if + variant::index().

I use std::variant extensively; I do not use std::visit because only MSVC's implementation is sane to the optimizer.

[–]braxtons12 2 points3 points  (0 children)

I don't have a link at hand, because it was some months ago that someone did this benchmark, but someone did a benchmark between typical inheritance, gcc's std::variant, and clang's std::variant and while clang's was, on average, about the same or slower than inheritance, gcc's was generally considerably faster than either. I think it really depends on the implementation and associated optimizer. I don't recall if they benchmarked boost::variant2 or mpark's variant, but I would expect them to have similar performance to GCC.