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!
132
Upvotes
89
u/tjientavara HikoWorks developer Feb 16 '26
[[no_inline]] / [[never_inline]] A very large optimization hammer than the name suggest.
Because the compiler is aggressively inlining functions [[always_inline]] is less effective than it used to be.
But marking functions that are called in the slow/contented path a [[no_inline]] will force the call to be an actual call, this will reduce the size of the function where the call is located and reduces register pressure, etc. This actually will cause more functions to be inlined and other optimizations.
71
u/theICEBear_dk Feb 16 '26
Best feats of optimization:
99
u/KFUP Feb 16 '26
25
u/cdb_11 Feb 16 '26
Packing things and comparing as a single 64-bit integer, for sorting.
19
u/Wargon2015 Feb 16 '26
std::vector::reserve
The first few insertions are surprisingly expensive due to reallocation. Its a trade-off but if you know roughly how many elements will be inserted, reserving can safe quite a bit of overhead.
16
u/usefulcat Feb 16 '26
This is a small, simple thing. I've often found that compilers are able to generate better code when more values are in local variables as opposed to member variables.
You might think that it shouldn't make a difference, but I think the problem is that the compiler often can't assume that member variables won't be modified by something the compiler isn't aware of. OTOH, it can usually make a lot of assumptions about local variables.
12
u/_Noreturn Feb 16 '26
using arrays for pretty much everything and writing clear code, and optimize when necessary
12
u/SkoomaDentist Antimodern C++, Embedded, Audio Feb 16 '26
I've done a fair bit of work in audio dsp and you'd be amazed how much mileage I've gotten from simple linear interpolation. Many things in that field don't require more than perhaps 1% accuracy as long as the residual error is smooth. As long as the result is roughly correct, has the right spectral shape, doesn't have nasty discontinuities and doesn't veer off into unstability, the exact details don't tend to matter hugely (as evidence see every real world psychoacoustics based audio compression method).
Need a fancy non-linear curve? Just use a linearly interpolated lookup table with some tens to hundreds of entries.
Need to calculate filter coefficients using a formula with tan() and division? Just interpolate from a small set of precalculated coefficients.
21
u/ArashPartow Feb 16 '26 edited Mar 15 '26
The following are commonly used in the context of low latency development:
Recommendation 0: Replacing std::map with std::vector + std::sort + std::lower_bound in a crit-path (aka hot path) where the dataset is built only once and queried many times. The asymptotics look worse on paper, but cache locality absolutely crushes tree-based approaches
Recommendation 1: Similar to Recommendation 0, when map like lookup functionality is needed and the number of elements are small, replace the map/set/unordered_map|set with a simple vector, the branchless tight loop (aka linear search) + perfect locality routinely beats hashing, pointer chasing, and cache misses.
Recommendation 2: When considering small vectors (ones where the underlying "data" can fit in L1 or better yet, fit in 1-4 cachelines aka ~4xstd::hardware_destructive_interference_size) where the specialisation type is a POD and order is not important, one can erase an element efficiently as follows:
Recommendation 3: Capture now (eg: std::chrono::steady_clock::now()) as a std::uint64_t, and do so only once per loop/iteration and reuse the time stamp within the loop if possible (aka loop body time will be less than "some" threshold). As the cost of now (or even as a call directly to something like __rdtsc ) has a very long-tail, and can be problematic in sub microsecond turn around time situations.
https://gist.github.com/ArashPartow/cea16480b425915337982ea6d556e2dc
Recommendation 4: In numerical computing, whenever possible try to avoid operating on denormal (subnormal) floating-point values as they can severely degrade performance.
A commonly used pattern involves applying weights, often derived from a function such as an exponential, to a sequence of values with a narrow range. The index of each value in the sequence is fed into the weighting function to derive the weight at that index and then applied to the value (multiplied), after which the weighted results may be aggregated (for example, via a sum or standard deviation) or used in further calculations.
If the weights cause the latter values to fall into the denormal range, any subsequent computations involving those numbers can become extremely expensive, and tbh they should already be assumed as being zero.
The solution here is to determine, in advance, given the range of the values, the maximum index beyond which applying weights from the function would produce denormal results and clamp the loop at that index/iteration.
In short the value represented by the floating point type (float, double, long double) can actually affect the performance of the mathematical operation being carried out making it anywhere from 5x to 100x more expensive. and NO enabling fastmath would not be advised.
Recommendation 5: The integer modulo operation can be VERY slow, in fact it can be slower than the equivalent floating point variant. Where required, try instead using a power of two value, as an example when wanting to do something every ten times (iterations), perhaps instead do the "something" every 8 or 16 times, that is if it doesn't change the business logic.
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=122101
Recommendation 6: When normalising a sequence of values to sum to a specific target value (eg: a probability distribution that must sum to one), avoid complex and inefficient floating-point adjustments that end up requiring spelunking in to the realms of nextafter or nexttoward. Instead identify the largest value in the sequence, normalise all other values BAU, then calculate the largest value's normalised result as: target - (sum of all other normalised values)
Recommendation 7: Be wary when using attributes such as [[likely]] and [[unlikely]], as they may make sense when coding up, but without proper representative benchmarking the results can be quite misleading and may not align with one's intuition.
Recommendation 8: Profile-Guided Optimisation (PGO) optimises for what happens most often in the profiling workload. In low-latency contexts (eg: HFT), the performance objective is frequently to minimise tail latency or optimise the critical 1% (or 0.1%) path rather than the common case (eg: Of the 1000s of market data updates it may be that only one will trigger a buy/sell event). PGO will naturally bias code layout and branch decisions toward the majority path, which can actively work against those goals if the rare but latency-critical paths are the ones that truly matter.
Recommendation 9: The noexcept specifier when used on methods and functions can be problematic as in the situations where the optimiser can't see through the call site (ABI boundary) to determine there truly are no exceptions that can be thrown, it has to mandatorily inject exception handling and terminate code, which can significantly reduce performance when the function/methods are being called in the crit-path. This can further be exacerbated when using policies, as with one specialisation the call site is visible for the optimiser, where as with another specialisation it may not be.
10
u/h2g2_researcher Feb 17 '26
I was reviewing some code used in a video game. It went through about 10 steps of trigonometric calculations based on a single input vector.
I sat down with a pen and paper, and did actual maths on the algorithm and found that the result was always just the
Zterm of the input vector, so we replaced the whole thing withreturn in.Z;and a comment explaining the mathematical justification for it.26
u/Big_Target_1405 Feb 16 '26 edited Feb 16 '26
People are generally terrible at implementing concurrency primitives because the text books / classic algorithms are all out of date for modern hardware.
People think for example that the humble thread safe SPSC bounded ring buffer can't be optimised just because it's "lock free" and "simple", but the jitter you get on a naive design is still very high.
In particular if you're dumping data from a latency sensitive thread to a background thread (logging, database queries etc) you don't want to use the naive design.
You don't want things just on different cache lines but also to minimize the number of times those cache lines have to move between cores, and minimize coherence traffic.
8
u/jayd16 Feb 16 '26
Deleting code.
15
u/Successful_Yam_9023 Feb 16 '26
It's prosaic but the thing I get the most mileage out of is just looking at the assembly my source code got compiled into. Looking at it doesn't make the code faster by itself, but if I hadn't looked I would just be blindly guessing about what to do next.
13
u/wynterSweater Feb 16 '26
Copy Ellison
12
u/Sopel97 Feb 16 '26 edited Feb 16 '26
In Stockfish we manually (as opposed to .text) replicate high-bandwidth eventually-read-only data on multiple NUMA nodes to get like 2-3x overall performance improvement on some hardware. https://github.com/official-stockfish/Stockfish/pull/5285
edit. it's also one of the reasons why we now have pretty much perfect thread scaling with extremely low variance even among the biggest machines https://openbenchmarking.org/test/pts/stockfish
6
u/mike_kazakov Feb 17 '26
Surprised
std::pmrhasn't been mentioned yet.It's a godsend when optimizing existing codebases.
An awful amount time is often spent on "let's collect these 5 elements in a vector, do something and then throw the vector away".
Which means malloc/free, caches trashing, potential synchronization etc.
A solution is often "here's 4K on stack and a polymorphic allocator, which should be enough for 99+% of cases".
In a case of an outlier or a malicious/corrupted input - the allocator gracefully backs off to a slow path.
4
u/JonathanECG Feb 16 '26
I don't have any one-size fits all tips, but I did want to call out for anyone daily driving a windows pc for development that at some point within the past year the WSL kernel has started to support hardware counters, allowing you to use `perf` and other downstream tools like https://github.com/brendangregg/FlameGraph while remaining on a windows host machine.
I'd still recommend being on the stack closest to what you're deploying on for truest of numbers, but it's been helpful for me to just have a script log out some microbenches representing the hot paths for every change. Coupled with valgrind for cache simulations.
4
u/Brisngr368 Feb 16 '26
-O3
7
u/mredding Feb 16 '26
In all seriousness, it's perfectly reasonable to abandon resources and teardown just to exit. WTF is the point of waiting to deallocate everything if the whole virtual address space is going to disappear anyway? Kernel resources bound to the process will be returned to the kernel. You should have a shutdown path that is independent of but used by object destruction so that a fast shutdown path will still guarantee persistence is flushed to the store.
We did this in video games.
It's also perfectly reasonable to strategically leak resources for performance - provided you do the analysis and know you can. This process only has to remain stable for 12 hours, and is guaranteed a restart on a strict schedule. We're not going to run out of space before then? We're not going to fragment out of our performance envelope before then? Then fuck it. I know it sounds dirty, but sometimes the faster path is worth it.
We did this in trading systems and web services.
It's often cheaper to scale hardware than software. You have to keep an eye on the numbers. Here's Bob. Bob spent 3 weeks optimizing the software to shave off 500 ns. Here's Frank. Frank added a new feature that costs 2.2 ms regardless of Bob's changes. Fuck Bob.
A $20k NIC card that guarantees 600 ns forever is cheaper than paying Bob for all the wasted effort. Bob could be doing something else more valuable what for the cost of his developer time.
We did this in trading and a cloud service platform. Hell, cloud service was all about horizontal scaling. We had hundreds and hundreds of R720s - latest tech at the time, and were plugging them in as fast as we could get them.
17
u/Ilyushyin Feb 16 '26
Reusing memory! I almost never return a vector or string from functions but have the function modify the vector, so you can use the same allocation(s) throughout your whole data processing pipeline.
Also using arena allocator whenever possible.
3
u/5plicer Feb 17 '26
Compile-time computation of lookup tables.
2
u/Shot-Combination-930 Feb 16 '26
My biggest wins have been using the right algorithms for the situation. Probably my biggest single win was changing some code that tested for hash/id collisions from using a comparison sort to radix sort. That one change reduced runtime for a single pass by several orders of magnitude, and that was by far the slowest part of that program.
2
u/gosh Feb 16 '26
I use a lot of different tricks and here is the latest Using the stack for stl container classes
documentation
code
2
u/msew Feb 17 '26
My favorite is when I upgrade visual studio and because I have ALL source code avail, I get an application wide improvement.
6
u/gnolex Feb 16 '26
Writing clean code is generally the best optimization technique. Write code that doesn't obfuscate intentions and the compiler is able to optimize it universally well. Only domain-specific use cases should go for manual optimizations and compiler intrinsics.
2
u/James20k P2005R0 Feb 16 '26
Swapping out inline functions, for inline code. Compilers still aren't sufficiently smart yet, so something like:
Can sometimes be slower than just inlining the body directly into where you need it. There seems to be some bugs internally in clang somewhere around returning structs from functions in some cases. Its not an inlining thing, as the architecture I was compiling for didn't support function calls
My favourite/biggest nightmare is floating point contraction. Another little known feature in C++ (that people endlessly argue against), is that these two pieces of code are not the same:
vs
C++ permits the latter to be converted to an FMA, but the former must compile to two instructions
Where this matters is again in GPUland, because a string of FMAs compiles to an FMAC instruction. Ie, given this expression:
This compiles down to:
Which is actually two fmac instructions, and a mul. Fmac is half the size of fma (and the equivalent add/mul instructions) as an instruction. Profiling showed me for my test case, that my icache was blown out, and this cuts down your icache pressure significantly for big perf gains in some cases (20-30%)
Depressingly this also means you can't use any functions because C++ <Jazz Hands>
1
u/ptrnyc Feb 16 '26
Made my own SIMD wrapper and got 3x speed gains.
Now there are several wrappers available but I still like mine better. It overloads most operations, so you can write your code in scalar using a template type set to float, then use SIMD<float, 4> instead of float and it just works.
1
u/MaitoSnoo [[indeterminate]] Feb 16 '26
expression templates and handwritten SIMD for calculations, pool and monotonic allocators, some alien tricks from Hacker's Delight
1
u/def-pri-pub Feb 16 '26
Part of this really depends upon the application space. For example, in the realm of computer graphics (and real time) approximations are great. My Ray Tracing in One Weekend implementation has a bunch listed.
Aligning for cache is also a great one.
1
u/Both_Helicopter_1834 Feb 16 '26
Lately I've been developing an alternative to std::shared_mutex, optimized for certain scenarios where the ratio of shared locks versus unique locks is very high: https://github.com/wkaras/C-plus-plus-intrusive-container-templates/tree/ru_shared_mutex . The implementation is in ru_shared_mutex.h/.cpp . I only need to flesh out the comments before I merge. The optimization is that, to obtain a shared lock, threads running on different CPU cores don't have to contend for a single cache line containing a counter of shared locks.
1
u/Gloinart Feb 16 '26
I like proxy classes, for example returning the length of a vector as a proxy class containing the squared length. As the length is often compared to other lengths, this automatically reduces two sqrt-operations per length-comparisson.
Combined with type safety as you cannot accidentally compare it to a regular float.
1
u/Alborak2 Feb 17 '26
My favorite one isnt cpp but rather system design. When running high performance polling code, you disable or keep idle the hyperthreads of the critical cores. Hyperthreading relies on most code being shit java that memory stalls constantly so it can interleave contexts, when youre actively using both threads, each is individuallly slower. I have a fun talk i gave on "how i made 'thing' faster by shutting off half the cpus".
You can do something similar with the dynamic turbo modes on cpus now too, where internally they have a power budget and clock faster the fewer cores are in use.
1
u/CocktailPerson Feb 17 '26
Being aware of aliasing rules is a big one. I once made a 30% improvement to some important code simply by passing some small structs by value rather than by reference. The compiler was tying itself into knots and constantly spilling registers because it couldn't assume that the references didn't alias.
1
u/DavePiper Feb 17 '26
Judy Arrays. The fastest hash search optimized for the best cache performance.
1
u/adamf88 Feb 17 '26
I see passing data by reference is so popular but may cause aliasing issues. Sometime just pass by value, little copy overhead at the beginning may highly pay off in hot loop.
1
u/scrumplesplunge Feb 17 '26
I quite like how clang and gcc can detect common patterns for bit operations and replace them with dedicated instructions. For example:
Clang and gcc can both optimize
read_uint32_little_endiantomovandread_uint32_big_endiantomov; bswapon x86-64, which is a little endian system that can load from unaligned addresses.This lets you write code which will work everywhere, but take advantage of hardware support where available.
1
u/mhfrantz Feb 17 '26
Favorite magic wand: tcmalloc
1
u/mattgodbolt Compiler Explorer Feb 18 '26
Not necessarily my favourites, but some gems amongst these: https://youtube.com/playlist?list=PL2HVqYf7If8cY4wLk7JUQ2f0JXY_xMQm2&si=rEu5UQ2EuNafCvii
0
u/GoogleIsYourFrenemy Feb 16 '26
Optimizing the code for readability.
If it's not in the hot path make it readable.
0
u/RazzmatazzAgitated81 Feb 17 '26
For some scientific calculation, I needed a structure to store the data like velocities, pressures etc on a 2D grid. My initial solution was a struct with these properties and then a 2D array of them - a AOS. The performance was bad so I had to use openmp.
But later I realized that a 2D array was a bad idea, and a SOA - structure of arrays would be much better. So I changed the entire thing and the performance improvement was massive, like under 1 second level. It became so efficient that parallelization with openMP became the overhead, meaning it would run in a single thread faster than it would in parallel...
1
u/nimrag_is_coming Feb 16 '26
classic duffs device, if only for the pure fuckery