r/cpp • u/Polarstrike • 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
264
u/[deleted] Mar 07 '24 edited Mar 07 '24
Unnecessary copying of objects, e.g. when passing an object as a function argument. Copying usually happens implicitly and silently thanks to the flexibility of C++ class constructors.
264
u/lightmatter501 Mar 07 '24
Not actually turning on the optimizer.
103
u/keelanstuart Mar 07 '24
Lots of allocs and frees all the time... and they're done implicitly by so many things (string, vector, etc)
24
u/Thesorus Mar 07 '24
using the wrong containers and algorithms.
6
u/findabuffalo Mar 07 '24
When people don't understand that the condition in the for statement executes every time and it's not just "loop this many times". Most common error is "for (int i=0; i < strlen(long_ass_string); i++)"
129
u/ConicGames Mar 07 '24
Not declaring a move constructor `noexcept` when it can. If not, `std::vector` won't be able to move objects when resizing and have to do a copy of everything. Also, `std::map` move constructor is *not* declared as `noexcept`, so resizing a `std::vector<std::map<...>>` can be quite expensive.
38
u/LongestNamesPossible Mar 07 '24
First is allocating memory inside heavily used loops.
Second is using lists or compound data structures like vectors of vectors when it isn't necessary (images where each line is a vector, things like that).
Standard linked lists are basically obsolete on modern computers. Granular memory allocation combined with pointer hopping means that allocation and accessing data probably exceeds the cost of using the data by a significant amount.
On top of that, when any multi-threading is brought in, all those memory allocations become even more of a bottleneck as the allocator either locks, or tries to manage allocation from multiple threads.
Allocation should never be a bottleneck in my opinion. If it shows up on profiling it is time to get it out of loops, preallocate and work with bigger chunks of data.
46
u/Ok-Bit-663 Mar 07 '24
Seen in a repository:
std:string* value=new std:string("something not important");
42
u/0xb9 Mar 07 '24
Accidental O(N2) complexity, e.g.:
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.
42
u/Ipotrick Mar 07 '24
not profiling regularly
14
u/DevaBol Mar 07 '24
Using strings instead of enums.
13
u/ContraryConman Mar 07 '24
Unnecessary copying. For example
To tbh the real answer is to run a linter like clang-tidy and a profiler like perf and let them tell you what's up with your performance. But a common theme is this, where you copy an expensive thing around instead of making use of emplacement or move semantics
12
u/The_Drakeman Mar 07 '24
Ran into this at work the other day. Auto doesn't pick up references in the type like it picks up pointers.
22
u/tsojtsojtsoj Mar 07 '24
Doing
instead of
11
u/LlaroLlethri Mar 07 '24
Algorithmic inefficiency (from implementing a completely wrong-headed solution to start with, to simply picking the wrong container), not utilising the hardware properly (naive single-threaded CPU code), inefficient memory access patterns, calling expensive functions too frequently, poor multithreaded design (lots of contention between threads). I guess these could all apply to any language though really.
3
u/Stormfrosty Mar 07 '24
Error checking is death by a million cuts. You don’t want to be doing unnecessary checks (e.g. bounds checking).
9
u/[deleted] Mar 07 '24
Assuming things without measuring them
16
u/HildartheDorf Mar 07 '24
Copies, copies everywhere (improved by c++11's move semantics, although it has gotchas if the move operation isn't noexcept, and often needs explicit guiding with std::move/std::forward. Also common optimizations were made mandatory in c++17)
Using algorithms with good big-O complexity, but terrible performance for the actual workload and hardware (e.g. any kind of linked list is almost always slower than std::vector unless your workload is in the 100s of MBs if not GBs).
std::deque as implemented by Microsoft
Not memoizing recursive functions.
Not caching network or disk requests
Caching without a good eviction policy. A cache with a bad (or no) eviction policy is a fancy way of saying a memory leak.
And one rather win32-specific pet peeve: Using a cross-process Win32 mutex when a std::mutex or Win32 CRITICAL_SECTION would suffice.
8
u/Extension_Split_8372 Mar 07 '24
Using a static local variable "to avoid creating it multiple times, so saving time" but actually the check whether it has already been created is more expensive than the creation. Bonus points if that local variable is a constant and the only runtime cost (if not for
static) would have been loading it: https://godbolt.org/z/P5G5eMMec (similar things have been seen in the wild)7
u/ReDucTor Game Developer | quiz.cpp-perf.com Mar 07 '24
Multi-threading, either none at all or poorly designed that it's scattered in locks fighting constantly to acquire them.
So many mentions of copying here, I feel the real issue is allocations. The c++ standard is awful and good in some ways letting you copy things which have external memory that needs allocating (e.g. strings, vectors, etc) and these copies are implicit and can be done accidentally very easily.
6
u/NilacTheGrim Mar 07 '24
Throwing exceptions as part of normal expected control flow. Exceptions are not for control flow! This isn't Python!!
5
u/ILikeCutePuppies Mar 07 '24
Not exactly c++ but iterating over an std::unordered_map or deleting it a lot. Using a std::list for just about anything as opposed than a std::vector (there are very few cases where std::list is more performant without changing out its allocator).
5
u/Fantastic-Raven Mar 07 '24
Writing the code with python
9
u/ButchDeanCA Mar 07 '24
Not making use of move semantics and if they do use them, they use them incorrectly assuming that moves have worked where actual copies have still taken place.
9
u/[deleted] Mar 07 '24
Overuse of shared_ptr, those atomics kill performance when used all over the place
12
u/[deleted] Mar 07 '24
your design :p
if you don't have performances in mind when designing your program , no amount of replacing little stuff will give meaningful results most of the time.
changing a variable to be a reference instead of value is simple.
changing your whole program design because it became too bloated with millions of additional superfluous instructions is really not simple
4
u/lronaldo Mar 07 '24 edited Mar 07 '24
I personally think that most common problem is lack of knowledge of how things work low level. It's quite common, IMHO, to rely on dimple rules and ideas on how things work. This works most of the time for developing and making things work, but doesn't work to understand many problems and, specially, to develop good quality, safe, secure and performant code. For that, knowledge and understanding is key, and our day to day exigencies and experience drives us to learn other things than this basic knowledge, if not directly disregarding it.
I routinely teach my students how important I think this knowledge is, and tell them that the bricks on the bottom of the wall are those which support all others: if those bricks are not perfectly placed, the wall won't be able to grow higher.
7
u/RishabhRD Mar 07 '24
7
u/geaibleu Mar 07 '24
Not very common but common enough: pointer aliasing, cache thrashing, and writing same cache line from two threads
1
u/hmoein Mar 08 '24 edited Mar 08 '24
Bad loop design
for (int I = 0; I <size; ++i) {
if (cond) do_this(i);
else do_that(i);
}
It should be
if (cond) {
for (int I = 0; I <size; ++i) {
do_this(i);
}
}
else {
for (int I = 0; I <size; ++i) {
do_that(i);
}
}
3
u/[deleted] Mar 07 '24
Forgetting to put the & where it belongs and using the wrong data structure when dealing with a lot of data.
3
u/No-Magazine-2739 Mar 07 '24
What most here say PLUS: Cache hostile programming. like for i for j array[i][j] vs array[j][i] . And false sharing
7
u/ilovecpp22 Mar 07 '24
std::shared_ptr
5
u/CandyCrisis Mar 07 '24
Using an ordered set or map when an unordered one would work just as well. It's not a massive penalty, but it definitely adds up.
6
u/NilacTheGrim Mar 07 '24
A dumb one: for a "heavy" iterator, doing
it++when all you really needed was++it. What you are really doing is telling the compiler to make an unnecessary copy when you sayit++(yes, yes, I know the optimizer can figure it out but not always and it just makes -O0 debug builds slower regardless)...4
u/yuehuang Mar 07 '24
std::endl;
2
u/AssemblerGuy Mar 07 '24
Unnecessary use of std::move that prevents RVO and causes move operations where there would have been neither copying nor moving.
2
u/frankist Mar 07 '24
Using std containers that are not std vectors everywhere or using std vectors of owning pointers.
4
u/CentralSword Mar 07 '24 edited Mar 07 '24
Some that I've encountered:
1
u/gc3 Mar 07 '24 edited Mar 07 '24
Passing huge arrays to a function by value by forgetting the & in the declaration of the function
1
u/bert8128 Mar 07 '24
Use of the wrong container type (eg list (almost always wrong), or using vector instead of maps/sets. This can have an effect of many orders of magnitude on large data sets (eg many hours rather than a few seconds).
1
u/NilacTheGrim Mar 07 '24
Not using
std::string_viewwhere appropriate -- and instead usingconst std::string &, thereby ensuring an extra copy if client code passes a C-style string. (NB:std::string_viewshould only be used for immediate functions that don't retain the string but just chew on it for some purpose before returning).1
u/[deleted] Mar 07 '24
Copying structs etc. Even when you are not going to edit the struct/object, the pointer method only takes 4-8bytes, instead of the normal struct size. If you dont wanna edit your existing code tho, use references.
1
u/DugiSK Mar 07 '24
These are a few that surprised me recently:
1
u/R2Sam Mar 08 '24
Seems like a lot of people have it out for std::vector. But what else are you really supposed to use when you want a list of object that you don't know the amount but is still reasonably small
1
u/saddung Mar 08 '24 edited Mar 08 '24
I'm surprised by all the upvotes for accidental copies, I can't think of any instance where that caused a serious performance issue--maybe in some code by new programmers back in the day(also should be really easy to spot in profiler if its a real issue)
For me I'd say these things:
1
u/TwistedBlister34 Mar 08 '24
Using std::map, list, set, or any cache-unfriendly data structures is death for performance. Make vector, colony, and other flat or mostly flat containers your defaults. They are almost always the best.
1
u/mikeblas Mar 08 '24
Using iostream
1
u/duane11583 Mar 08 '24
one guy set up a switch case statement using strings
for every byte in the large file being parsed it was using strcmp() for each switch case entry.
said the tool sucked and was horrible.
i was asked to optimize and help.
he had no clue….
1
u/[deleted] Mar 08 '24
N3 loops
Big strings use string ref not copy
Vector copying
1
u/[deleted] Mar 09 '24
Using shared pointers everywhere.
1
u/ed_209_ Mar 09 '24
I recently discovered that compiling with split-stack was causing a 6X slowdown. This was in a game tree search which entirely revolves around using the stack aggresively i.e. 100M moves a second via depth first search.
1
u/[deleted] Mar 10 '24
Overuse of templates and some idiomatic C++ constructs.
1
u/asergunov Mar 08 '24 edited Mar 08 '24
My biggest mistake is to write algorithms by myself instead of using well known libraries. Some of them are in Python especially in scientific field. Consider to use them. Python is great as a glue between high performant C++ code.
Next is using CPU instead of GPU. I imagine GPU like configurable conveyor. Let’s say you need to make M operations on each of N elements. On CPU it will take MxN/cores. On GPU you configure you conveyor of M units once and push elements on one side and take from the other. So it’s N+M operations in total. But once you have KxM units available you can make K conveyors so it will give N/K+M.
If we are still on c++ land:
1
u/BrangdonJ Mar 07 '24
Most of the things that mattered were too specific to my app to be common. Most of them amounted to taking something that was fast enough as a one-off, and putting it into a loop.
For example, composing a page of text takes maybe 30ms. Composing 1,000 pages takes maybe 30 seconds. (I worked on desktop publishing.)
Lots of things that are theoretically bad, like passing by-value when by-reference would be better, didn't actually matter in practice. Some with deleting from vectors one at a time.
1
u/paranoidzone Mar 07 '24
vector<bool> is just terrible for performance depending on the application.
1
u/Constant_Physics8504 Mar 07 '24
Calling functions in conditions for multiple branches. Like: if(errorPresent() == Errors::FAIL){ doSomething(); } if(errorPresent() == Errors::FNF){ doSomethingElse(); }