r/programminghumor • u/Bubbly_Rain7858 • Jun 13 '26
How to REALLY optimize code.
My friends, this is how you optimize code correctly.
97
Upvotes
r/programminghumor • u/Bubbly_Rain7858 • Jun 13 '26
My friends, this is how you optimize code correctly.
View all comments
Show parent comment
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.