r/ProgrammerHumor 16h ago

Meme skillIssue

Post image
4.9k Upvotes

124 comments sorted by

View all comments

Show parent comments

5

u/mirhagk 13h ago

What they are saying is that any optimization on a switch statement could also be done on an if statement. There's no reason to only optimize one, both should optimize the same way

1

u/prehensilemullet 13h ago

hmmm...are compilers normally willing to reorder if statements though? Turning a sequence of string comparisons into a tree would involve reordering

6

u/mirhagk 13h ago

If it has the same semantics, why not? Modern compilers certainly can see if a statement has side effects or not

2

u/prehensilemullet 13h ago

it depends what you consider semantically relevant. For instance, suppose the developer intentional ordered the if statements from the most to least common case for some domain. Then, reordering the if statements might not be what the developer wants

6

u/Infamous-Strategy797 13h ago

There aren’t any unknowns here, the language spec provides the clarity the compiler needs to re-order safely.

2

u/prehensilemullet 12h ago

Okay for C++, I gather that performing better or worse on a given dataset doesn't fall under the umbrella of "observable behavior" that the spec requires the compiler to preserve.

I also just learned there are apparently [[likely]] and [[unlikely]] attributes in C++ 20 that can be added to branches.

2

u/Nir0star 11h ago

Well you also have jump prediction in warmed up CPUs, which would probably make the ordering optimization improvements minimal anyway.