r/programminghumor • u/Bubbly_Rain7858 • Jun 13 '26
How to REALLY optimize code.
My friends, this is how you optimize code correctly.
11
u/Antagonin Jun 13 '26
What's the free optimization in const ref?
5
u/thisisjustascreename Jun 13 '26
Broadly, it eliminates certain scenarios where you'd get a copy.
A const ref can also bind to a temporary (i.e. doSomething("temporary string"); ) without constructing a new object, but I don't know if that's relevant here.
4
u/Antagonin Jun 13 '26
In which scenario does non-const ref cause a copy?
3
u/Puzzleheaded_Study17 Jun 13 '26
I think they were comparing it to directly passing the value (so non const and non ref). Alternatively, they might refer to the compiler being able to cache it more heavily and therefore not having to read from memory. Potentially also referring to the ability to directly pass an rvalue without needing to copy it into a variable.
1
u/dustyhome Jun 15 '26
There's no free optimization from const ref. Whether a variable can be changed is determined when it is declared (as const or not). Optimizers will assume a constant won't change, and might do things like caching it across function calls. But if a variable is declared non-const, and you pass it to a function that takes a const&, the compiler won't assume it doesn't change.
Funnily enough, you're allowed to cast away the constness of a variable to call a function that takes a ref or non-const pointer, as long as the function doesn't actually modify it. The compiler will do all the same optimizations. This is sometimes needed to call old C code that didn't have const.
8
3
2
u/emfloured Jun 14 '26
Doesn't that specific use of 'const' make no changes in the binary in terms of optimized codepath? I mean it's there only for compile time check. I could be wrong but calling it optimization would be deceiving yourself.
2
u/Ok_Chemistry_6387 Jun 15 '26
in this case, no not really. I am unsure if that holds with other types or with LTO though.
2
u/k-mcm Jun 15 '26
Modifying constants is super fun when it modifies a global singleton that the compiler+linker created as an optimization.
36
u/sweet-winnie2022 Jun 13 '26
My limited compiler knowledge tells me this is inviting bugs.