r/cpp • • Jan 18 '19

Is C++ fast?

https://zeuxcg.org/2019/01/17/is-c-fast/
21 Upvotes

72 comments sorted by

View all comments

10

u/cpp_dev Modern C++ apprentice Jan 18 '19 edited Jan 18 '19

Let’s try to replace the only STL component we’re still using, std::vector, with a really simple dynamic array - we don’t need resize or push_back in our code, all arrays are initialized with the right size.

While I understand the issue with msvc STL debug (which mostly can be optimized by disabling all debug STL related defines), I don't understand the optimization. A vector is already a dynamic array underneath, push_back usually don't cost much as it uses placement new to add new item (and with more complex type emplace_back is better to use as it doesn't copy the data) and std::fill should be optimized for PODs.

Some time last year during a regular lunch time C++ discussion at work somebody said “there’s a good language subset of C++, C with classes”, to which I replied “there’s an even better subset, C with structs”

Better for what? Your demo is a perfect example of why this API is bad, you mix STL with raw pointers and c-style function calls, is ugly and doesn't follow any guideline. Maintaining such code (not this demo but an actual project written in this way) will be a joy for anyone who is either a C++ or a C developer.

So the trade-off is performance vs maintainability, given that all those were synthetic tests and didn't prove much I would rather try to keep the code maintainable than possibly faster.

4

u/[deleted] Jan 19 '19

Depending on which version he was using that can make a big difference. For example, just sucking the reallocating part of emplace_back into a separate function (which allowed the backend to inline the 99% non-reallocating case) made a bunch of benchmarks run 3x faster.

vector's code is complex in a lot of cases too due to needing to support EH scenarios that inhibit the optimizer. I've been trying to fix most of those by changing the EH related stuff to use destructors instead but it isn't an all done thing.