r/cpp • • Jan 08 '21

With std::variant, you choose either performance or sanity

https://www.youtube.com/watch?v=GRuX31P4Ric mentioned std::variant being an outstanding type. Previously, I had been using untagged unions for the same purpose, manually setting a tag field.

My conclusion is that std::variant has little benefit if performance is important. "Performance", in my case, means my main real-world benchmark takes 70% longer to complete (audio). So std::variant's overhead is approximately as expensive as everything else in my program together.

The reason is that you cannot do dynamic dispatching in a simultaneously reasonable and performant way. Untagged unions suck, but std::variant doesn't solve the problems with untagged unions it wants to solve. Here's how dynamic dispatching is done:

if (auto* p = std::get_if<0>(&a))
    return p->run();
else if (auto* p = std::get_if<1>(&a))
    return p->run();
else if (auto* p = std::get_if<2>(&a))
...

You copy and paste, incrementing the number each branch. Any time you add or remove a type from your variant, you must also adjust the number of else if(), and this must be done for each dispatch type. This is the very stupid stuff I've been doing with untagged unions. If we try to use std::variant's tools to avoid this, we get https://stackoverflow.com/questions/57726401/stdvariant-vs-inheritance-vs-other-ways-performance

At the bottom of that post, you'll see that std::get_if() and std::holds_alternative() are the only options that work well. std::visit is especially bad. This mirrors my experience. But what if we use templates to manually generate the if-else chain? Can we avoid copy-paste programming?

template <int I>
struct holder {
    static float r(variant_type& f, int argument) {
        if (auto pval = std::get_if<I - 1>(&f))
            return pval->run(argument);
        else
            return holder<I - 1>::r(f, argument);
    }
};
template <>
struct holder<0> {
    static float r(variant_type& f, int argument) {
        __builtin_unreachable();
        return 0;
    }
};

holder<std::variant_size_v<variant_type>>::r(my_variant, argument);

That looks ugly, but at least we only have to write it once per dispatch type. We expect the compiler will spot "argument" being passed through and optimize the copies away. Our code will be much less brittle to changes and we'll still get great performance.

Result: Nope, that was wishful thinking. This template also increases the benchmark time by 70%.

mpark::variant claims to have a better std::visit, what about that?

  1. It's annoying converting std::variant to mpark::variant. You must manually find-and-replace all functions related to std::variant. For example, if get() touches a variant, you change it to mpark::get(), but otherwise you leave it as std::get(). There's no way to dump the mpark functions into the std namespace even if ignoring standards compliance, because when some random header includes <variant>, you get a collision. You can't redefine individual functions from std::get_if() to mpark::get_if(), because function templates can't be aliased.
  2. Base performance: mpark::variant is 1-3% slower than std::variant when using if-else, and always slightly loses. I don't know why. But 3% slower is tolerable.
  3. mpark::visit is still 60% slower than a copy-pasted if-else chain. So it solves nothing.

Overall, I don't see a sane way to use std::variant. Either you write incredibly brittle code by copy-pasting everywhere, or you accept a gigantic performance penalty.

Compiler used: gcc 10.2, mingw-w64

152 Upvotes

121 comments sorted by

View all comments

Show parent comment

7

u/zfgOof Jan 08 '21

Thanks, I'll try that and get back. Your description exactly matches my use case.

11

u/zfgOof Jan 08 '21 edited Jan 08 '21

Unfortunately, boost.variant2 does not have good performance. However, it's better than the other variants.

If-else chain: boost.variant2 is 2-3% slower than std::variant. No idea why; maybe it's the double storage. I use -fno-exceptions and my program never throws except to abort(), but it's normal that code can't detect it. It's 544 bytes with std::variant, and 1080 bytes with boost.variant2.

visit(): boost.variant2 runs in 39.7 seconds, vs the if-else chain running in 31 seconds. That's only a 28% time increase.

My flags are: -Ofast -DNDEBUG -fno-exceptions -fno-rtti -march=native -flto

7

u/MrPotatoFingers Jan 08 '21

If you get double storage there is something wrong with one of your types. If they all have proper move constructors marked noexcept you should not need it.

10

u/cdglove Jan 08 '21

Yup. People think they can ignore noexcept if passing -fno-exceptions, but you can't -- the type traits still need it.

0

u/zfgOof Jan 08 '21

I marked my move constructors as deleted. The objects are nonmovable, and are also never moved. variant2's detection can't catch this case, which is reasonable.

13

u/MrPotatoFingers Jan 08 '21

If it cannot move them, it must construct the elements in place. If that cannot be done safely (i.e. you forgot the noexcept) it uses double storage so it can first construct the new instance before destroying the old one.

If your constructor is noexcept, it knows construction can't fail so it's safe to destroy the old instance and then creating the new one in the same memory.

2

u/zfgOof Jan 08 '21

I'm aware of the issues and think it's acceptable that variant2 doesn't catch it, which is why I didn't complain too hard in the beginning. The semantics around being exception-free are a general C++ problem, not a variant2 problem. A policy-based variant2 would be more suitable for my case, since I know that I also avoid all those issues. The original boost::variant was cognizant of this problem and mentioned it, but did not get around to finishing it.

10

u/MrPotatoFingers Jan 08 '21

There is nothing for boost.variant2 to catch. Even if you had another way to get it to avoid double storage besides the obvious noexcept qualifications, you're likely still throwing away performance elsewhere - think a vector where you do a push- or emplace_back that now takes the slow path to be exception-safe.

If you want exception-free programming, just mark your functions noexcept.

4

u/zfgOof Jan 08 '21

I just assumed you were right about failure to catch it being my responsibility, since I know that catching noexcept is hard and I didn't bother being careful about it.

However, it turns out boost.variant2 just doesn't catch it. My move and copy constructors are all deleted or noexcept. My constructors are all noexcept. There is nothing wrong with my types.

If I feed variant2 with a struct with a deleted move constructor, it doubles the storage, because its check is mp11::mp_all<std::is_nothrow_move_constructible<T>...>::value and it ignores when the move and copy constructors doesn't exist. So it's very easy to catch in this case, and it's variant2's fault.

4

u/dodheim Jan 08 '21

What do you propose it check instead of std::is_nothrow_move_constructible?

2

u/zfgOof Jan 08 '21

If my move constructor is deleted, it can't be called, so it doesn't matter that it's not noexcept. std::is_move_constructible captures this information.

→ More replies

4

u/pdimov2 Jan 09 '21

Please open an issue.

5

u/Olipro Jan 08 '21

As a quick note. I'm sure you know exactly what `-Ofast` does, but anyone else considering using this: It has a profound impact on certain mathematical operations; you need to carefully read and understand what it enables before using it.

1

u/axalon900 Jan 08 '21

A bit like using /dev/null for maximum I/O throughput.

5

u/pdimov2 Jan 09 '21

I looked at your other posts and there's a link where you show 5 alternatives, each with a run(float) function, so that's what I tried: https://godbolt.org/z/PsEqxa

visit generates the exact same code as the manual switch, which for five types is a jump table. Disabling the copy constructor in X1 leads to double storage, which makes the code no longer look so good, but there's room for improvement in Variant2 about this case. You can try, as an experiment, to add dummy noexcept move constructors to your types so that double storage is avoided and see if this helps. (As another experiment, you may try replacing the two occurrences of

constexpr std::size_t index() const noexcept
{
    return ix_ >= 0? ix_ - 1: -ix_ - 1;
}

in variant.hpp with

constexpr std::size_t index() const noexcept
{
    return (ix_ >= 0? ix_: -ix_) - 1;
}

which will eliminate a branch in the double storage case. Apparently GCC 10.2 is smart enough to see the inlined abs in the second case and use branchless code for it, but subtracting 1 from both sides is enough to disable this optimization.)

3

u/zfgOof Jan 09 '21

Your 1 line per case is the best code I've seen generated. Testing in clang, the add rdi, 4 gets bumped into the case and duplicated, but this is still better than everyone else. https://gcc.godbolt.org/z/6b5eaW

Second best in clang is mpark::visit, producing 3 lines per case, from https://www.reddit.com/r/cpp/comments/kst2pu/with_stdvariant_you_choose_either_performance_or/gimhghh/ However, once anything is done after the visit() call, the cases blow up to a much larger size.

u/quicknir

2

u/zfgOof Jan 09 '21

I went into variant2 and replaced all the nothrow checks with true, and deleted the static assertions. This eliminates the double storage.

Under this situation, variant2::visit is slower than mpark::visit on my benchmark by 0.7-1.3% consistently. mpark::visit is currently the fastest in my benchmark, but it randomly loses its crown when the benchmark is tweaked in seemingly irrelevant ways. mpark handles exceptions, so variant2 appears not to gain benefits from its stricter contract. But from my testing, I think these visit() problems may be a codegen issue of the compiler, rather than a library issue.

4

u/pdimov2 Jan 09 '21 edited Jan 09 '21

You previously said that "mpark::visit is still 60% slower than a copy-pasted if-else chain" and that variant2 is 28% slower than the if-else chain. Does that mean that single storage variant2 also slows down to become 61% slower, or are we talking about different numbers?

But from my testing, I think these visit() problems may be a codegen issue of the compiler, rather than a library issue.

For variant2::visit, the goal is to produce the exact same code as a hand-written switch. Whether that's better or worse than an if-else chain is up to the compiler optimizer and the branch predictor. Clang for instance turns an if-else chain back into a switch and then into a jump table, so there should be no difference there. In fact looking at the codegen https://godbolt.org/z/oGrvbd the hand-written switch is actually worse than the other two for some reason.

In real code it would depend on whether run can be inlined, whether the run functions are similar, and whether the compiler can exploit the similarity. In some artificial cases such as https://godbolt.org/z/jjK58n / https://godbolt.org/z/oh19fK the switch can vanish entirely, but the optimizations are quite fragile as you can see.

Edit: interestingly, this is an area where GCC has actually regressed; g++ 9 optimizes out the switch consistently in the last example, in any form: https://godbolt.org/z/GKKoMr

I thought I had reported this as a GCC bug but it turns out that the code in my report is more complex. https://gcc.gnu.org/bugzilla/show_bug.cgi?id=92005

2

u/zfgOof Jan 09 '21

Different numbers. mpark::visit and boost2::visit are now among the fastest performers in my benchmark under different circumstances, and beat a hand-written switch. They are either performance leaders or within 3% of the performance leader. The reason they have gone from losers to winners is apparently for nothing logical I can see, because my benchmark is still testing the same thing. In addition, under benchmarking, the hand-written switch is usually slow, which I'm going to write a huge post about soon.

3

u/dodheim Jan 09 '21

At a certain point, one begins to suspect your benchmarking harness... ;-]

3

u/zfgOof Jan 09 '21

:)

I have experience benchmarking, and it verifies its results (check correctness, prevent DCE). However, it doesn't use tools like Stabilizer which I would want it to, since Stabilizer looks increasingly relevant for this case. I know it's not satisfactory to have an opaque benchmark from someone saying "trust my experience", because I would be unhappy with this too. Benchmarking is hard and error-prone, even for experienced people. Unfortunately, it would take a monstrous amount of work to reduce it to a testcase I would consider publishing, to preserve anonymity.

Also, the results are strange, but it's clear that the effects are real because I can replicate the assembly problems in godbolt. Things that are slow for seemingly no good reason in my benchmark also show strange assembly for seemingly no good reason in the godbolt link (which is in the new post).

2

u/pdimov2 Jan 09 '21 edited Jan 09 '21

How does your visit call look like? visit([](auto& x){ x.run(); }, v);?

How do the alternatives look like, roughly? How many of them are there?

2

u/witcher_rat Jan 08 '21

However, it's better than the other variants.

Heh, nice pun.