r/cpp • u/Little-Reflection986 • Feb 16 '26
Favorite optimizations ??
I'd love to hear stories about people's best feats of optimization, or something small you are able to use often!
135
Upvotes
View all comments
Show parent comment
6
u/theICEBear_dk Feb 16 '26 edited Feb 16 '26
It can mean two things. For one it can be as /u/spooker11 says just use a Hashmap to make a super simple cache.
But it can also be to use a data structure that fits in the L1, L2 or L3 caches of the processors you are dealing with to reduce the amount of times you have to expensive accesses either to the main memory or similar. Like maybe you can accept having slightly out of date data in a local cache because you would need to go over the local network maybe even using distributed locking to have absolute consistency of your data. On top of that there can be things to think about if you are operating on a platform where the cpu or gpu caches are distributed across cores so that you pay a communication cost for accessing them that is lower than RAM but can cause CPU stalls or just delays.
In general though the best advice is often: use an array or vector (contiguous memory), try to avoid copying it instead pass around ownership and only really think about it if you need to optimize.
It also really matter how you organize your data. For example in a lot of games they structure data more like arrays to be processed than objects that are accessed. OO has its place, so does that more stream oriented method (and often the abstract structure of the program is still OO-ish). Just like OO can be hugely misplaced and overapplied, the people who think OO is never to be used should be ignored as much as those who say that functional programming is a bad idea.