Home > Back-end >  complexity of std::variant operations
complexity of std::variant operations

Time:12-24

In std::holds_alternative and std::get_if documentation, it does say what's the complexity requirements of the operations. Are the two functions always O(1), or it's linear in terms of number of types in the std::variant? Another way to ask is is there any difference in terms of performance of the two operations on variants that has many member types vs. very few member types.

CodePudding user response:

The most reasonable implementation of a variant is an index integer denoting the type (also accessible through the index() method) and aligned storage for the held value.

Since the type argument for holds_alternative and get_if is a template, the type to index computation can be done at compile time. Therefore the runtime check is performed in const time. Just a simple integer comparison.

Some variant methods describe time complexity. For example visit:

For n ≤ 1 [n = number of visited variants], the invocation of the callable object is implemented in constant time, i.e., for n = 1, it does not depend on the number of alternative types of Variants0. For n > 1, the invocation of the callable object has no complexity requirements

This backs up my assessment

  • Related