r/cpp • u/pavel_v • Oct 21 '25
When Compiler Optimizations Hurt Performance
https://nemanjatrifunovic.substack.com/p/when-compiler-optimizations-hurt
68
Upvotes
r/cpp • u/pavel_v • Oct 21 '25
50
u/ReDucTor Game Developer | quiz.cpp-perf.com Oct 21 '25
I feel a more intuitive way to understand low level performance like this is to think of the backend part of the CPU as a data dependency graph, where parts of keep getting added on many of them are just predictions of what will be added and when it gets it wrong then it needs to throw them away and start again.
So let's assume that your using the jump table version in a loop like
Assuming it's mostly inlined and the jump table was even more simplified down to
If you look at each
pit's dependent on the data being loadedseq_size[*p]which is dependent on the data loaded from*pso it becomesBut this is just a single iteration, the next iteration depends on the previous so it's more like
If you keep going, it's just one really long line if individual loads to determine where to do the next load, there leaved limited room for out of order execution, even though they are all things that should be in the L1 cache due to previous usage and hardware prefetching.
However if you compare it to something like
Where the majority of cases will hit the
*p < 127then the branch predictor will end up just queueingp += 1and I'm sure you can work out what the data dependency graph for it will look like (the immediate1)13
u/Nicksaurus Oct 21 '25
I wonder how much the performance depends on the dataset. Presumably for English UTF-8 text the sequence length is almost always 1 so the branch predictor is almost always correct. Maybe the results are different for other languages that use a lot of longer character encodings? I wouldn't expect it to make a huge difference but I'd be interested to see if it has any effect
17
u/Bisqwit Oct 21 '25
I prefer the integer-as-a-table approach. Branchless, no memory read operations.
https://godbolt.org/z/7jG9fqqPq
9
u/FrogNoPants Oct 21 '25
Optimizing while only processing 1 byte a time, and having a switch statement(that basically does nothing) is certainly a choice..
If you are optimizing instructions and not using SIMD, you aren't really optimizing, and also don't stick switch statements in inner loops.
2
u/Sopel97 Oct 21 '25
and what happens with PGO?
Without PGO compiles lack necessary information to choose a faster implementation here, and I'd consider using
switchto indicate that a jump table is preferable in any case. If you want branches with high likelihood then use branches.0
u/[deleted] Oct 21 '25
[deleted] — view deleted comment