2

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.

Chen Li
  • 4,824
  • 3
  • 28
  • 55
Ishita
  • 489
  • 5
  • 15
  • You measured something and you want a source from the internet to tell you if that's true? Typically, I tend to downvote people who want numbers from the internet and are too lazy to measure themselves. IOW, it's odd that you did everything right, just trust yourself! However, if you would like others to repeat the measurements on their systems, you'd have to provide the full code. – Ulrich Eckhardt Jan 07 '19 at 08:11
  • @UlrichEckhardt What I was really looking for on internet is that has anybody else ever done a comparison among these two! or anyone who already knows which one is better to use! This is because, I got major performance gain in the sample code, but 'get()' and 'apply_visitor()' both gave nearly similar performance in my production code. I do not want to blindly use any of these in the production code. – Ishita Jan 07 '19 at 09:12

0 Answers0