r/programminghumor • • Jun 13 '26

How to REALLY optimize code.

Post image

My friends, this is how you optimize code correctly.

97 Upvotes

13 comments sorted by

39

u/sweet-winnie2022 Jun 13 '26

My limited compiler knowledge tells me this is inviting bugs.

8

u/realmauer01 Jun 14 '26

It shouldn't if the variable is already considered as not constant.

That being said, it just does nothing.

The idea behind it is that it "ensures" that the compiler looks ahead and repalces every path where the variable is actually const already. While it obviously cant do that on paths where it isnt. Funnily enough that is standard behavior already, no matter if a variable is const or not.

5

u/qaCow37 Jun 14 '26

Its all fun until you pass a variable marked as static and constexpr.

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.

→ More replies (1)

9

u/agufa Jun 14 '26

The only one laughing here is the compiler optimizer

3

u/ArmchairmanMao Jun 13 '26

This is very silly

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. 

2

u/[deleted] Jun 14 '26

[removed] — view removed comment

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.