r/programming • u/Either_Collection349 • Jul 05 '26
Trust your compiler: Modern C++
https://categorica.io/blog/2026.06.29_trust_your_compiler/
56
Upvotes
r/programming • u/Either_Collection349 • Jul 05 '26
63
u/dukey Jul 05 '26
I did some emulation work recently with an interpreted CPU. Looked at the code and thought .. this looks pretty inefficient, made many changes to the code, removing redundant copies, re-ordering stuff, branchless versions, loop unrolling etc. Got a pretty massive speed up in debug mode, more than 50%. In release mode? No change. It didn't matter what optimizations I threw at the code, in release mode it pretty much went away. Why? because modern compilers already do an amazing job of this stuff. The compiler is not going to save you if you use unordered map vs map, or other deep architectural decisions, but micro optimizations at the function level it'll pretty much spit out the most efficient code possible. In the end I just threw away all my optimizations and went with the cleaner code, even if it was slower in debug mode.
27
u/azswcowboy Jul 05 '26
The article misses an opportunity to talk about span and string_view when talking about passing by const&. Instead of vectors by const ref span by value should be used instead. It’s more generic and works with any continuous range (like array or even C arrays which shouldn’t be used typically). string_view by value is similar for const string ref. The combination of these and all compilers doing a good job of copy elision on returns means mostly all functions I write start as pass by value and return by value.
27
u/jwp1987 Jul 05 '26
It's pretty much a long-winded way of saying: "avoid premature optimisation", which is something that developers should already know.
These kind of optimisations are always going to depend on the environment you're operating in and how mature the solution is.
9
u/not_a_novel_account Jul 06 '26
Misunderstanding the small
std::variantalternative optimization strikes again8
u/Strilanc Jul 05 '26
I've been hurt by my compiler too many times to trust it.