std::variant
is generally very efficient, offering performance characteristics similar to a union. The key performance features are:
std::get
and std::get_if
functions are generally implemented as constant-time operations.In comparison to other approaches:
However, there are a few potential performance pitfalls to be aware of:
std::visit
with a lambda that has a complex template parameter (like auto&&
), this can lead to significant code bloat, as the lambda will be instantiated for each possible variant type. For maximum performance, prefer simple visitor functions.std::get
when the type doesn't match, or assignment/emplacement when the type's move/copy operations could throw) can be slower due to the need for exception handling. Avoid exceptions where possible for maximum performance.std::unique_ptr
to the large type instead.Despite these potential pitfalls, std::variant
remains a highly performant choice for type-safe value-based polymorphism in most cases, offering better space and time efficiency than alternatives like inheritance.
Answers to questions are automatically generated and may not have been reviewed.
std::variant
Learn how to store dynamic data types in C++ using unions and the type-safe std::variant