‹ BackHN Continuity

Thread

Writing Efficient C++ Code (2013)

176 points · 161 comments · ibobev

  1. hn_submit · · focus · HN ↗
    I write in C++ almost every day but never have the need to optimize for speed. Even when you write straightforward code it's already blazingly fast.
    1. glouwbug · · focus · HN ↗
      True, but moving from a list of unique polymorphic pointers to a std::variant gains you at least a 2-3x speed up in terms of TLB and cacheline locality. From there, swapping to SOA will net you another 4-8x, so you're looking at nearly 25x improvement by going data first. That may not matter in the unique case of say, games, where rendering a million entities will dwarf the cost of SIMD processing a million entities, but in something like numerical simulations (fluids) or quant it will be warmly welcomed
      1. tcfhgj · · focus · HN ↗
        are you sure?

        <a href="https:&#x2F;&#x2F;stackoverflow.com&#x2F;questions&#x2F;69444641&#x2F;c17-stdvariant-is-slower-than-dynamic-polymorphism" rel="nofollow">https:&#x2F;&#x2F;stackoverflow.com&#x2F;questions&#x2F;69444641&#x2F;c17-stdvariant-...

        1. creata · · focus · HN ↗
          If you take the linked benchmark and use the latest compiler version, the std::variant version is faster. The annoying thing about std::variant (and with some other features of modern C++) is that it generates a bunch of code that the compiler has to optimize away.
          1. vlovich123 · · focus · HN ↗
            Somehow and for some reason rust enums don’t have this problem and are far more ergonomic and easier to work with (not to mention compile times are amazing). I don’t know exactly why it’s better to have it as a first class language primitive and why the compiler has such a problem with std::visit, but clearly c++ meta programming slows down things in a super linear way such that the compiler has problems both from code gen and then optimization.
Open on Hacker News to reply ↗

Unofficial Hacker News client; not affiliated with Y Combinator.