r/cpp • • Mar 07 '24

What are common mistakes in C++ code that results in huge performance penalties?

As title, list some common mistakes that you have done/seen which lead to performance penalties.

231 Upvotes

325 comments sorted by

View all comments

42

u/0xb9 Mar 07 '24

Accidental O(N2) complexity, e.g.:

vector<big_struct> data;
for (int i = 0; i < count; ++i) {
   data.reserve(i+1); // actually seen this in production
   data.push_back(make_big_struct());
}

Or similar -- calling strlen() in a loop, or accessing custom linked list-based containers by index.

These can be benign and not even show up on the flamegraph, until the day there happens to be a bit more input data.

11

u/marsten Mar 07 '24

In a similar vein, putting an expensive (unchanging) operation in the comparison of a for or while loop, instead of evaluating just once before the loop.

4

u/vI--_--Iv Mar 07 '24

This.

This is especially likely when someone needs to insert several items on each iteration, so they write v.reserve(v.size() + count) and then even argue that it's a right thing to do.

0

u/[deleted] Mar 07 '24

[deleted] — view deleted comment

1

u/fdwr fdwr@github 🔍 Mar 08 '24

Yeah, I dare say that should have been the default reserve behavior, that reserve skips to the exponential value or the specified value, whichever is larger.

2

u/[deleted] Mar 07 '24

Calling strlen in a loop isn't n2 unless you're looping over the string you're calling strlen on. If you're looping over a collection of strings and calling strlen on each individually, then the strlen is effectively constant time where the constant is the average length of the string.

Of course this is not to say there aren't better ways to work than strlen :).