I am using boost::variant
and wanted to know which is a better(in terms of performance) approach to extract the values from the variant.
With my performance benchmark, on a sample data, I found that apply visitor is faster, but I didnt find any documentation on internet, which confirms the same.
Also, debugging/profiling the get()
and apply_visitor
workflow, doesn't indicates why the latter is faster over the former.
Anyone, who can comment upon this behavior or justify the results.
I would want to prefer using apply_visitor only if it is faster than get.
P.S. this is not a duplicate of boost::get vs boost::apply_visitor when fetching values from a variant
Here is my code with an example:
struct A
{
.....
};
struct B
{
.....
};
boost::variant<A, B> myVar;
I am able to fetch the values of A
or B
using either of the following ways:
using boost::get()
switch(myVar.which())
{
case 0:
auto a = boost::get<A>(myVar);
break;
case 1:
auto b = boost::get<B>(myVar);
break;
}
using apply_visitor()
class visitorA : public static_visitor<std::optional<A>>
{
public:
template <typename T>
std::optional<A> operator() (const T &val) const
{
return std::optional<<A>>(nullopt);
}
std::optional<A> operator()(const A &val) const
{
return std::optional<A>(val);
}
};
auto optA = apply_visitor(visitorA, myVar);
if(optA )
auto a = optA.value();
auto optB = apply_visitor(visitorB, myVar);
if(optB)
auto b = optB.value();
There will be a similar definition for visitorB
to fetch values of type B
( I am avoiding it here to keep things simple)
Performance Comparison Results, timings(in Micro sec):
For 100000 Iterations:
- get 336
- apply 228
For 1000000 Iterations:
- get 3694
- apply 2266
Note: These are the timings when variant is of User defined types.
For a variant of <int, std::string>
, get was faster.
I have variant of User defined types and so am particularly interested in the performance of that.