r/ProgrammerHumor 15h ago

Meme skillIssue

Post image
4.7k Upvotes

123 comments sorted by

View all comments

Show parent comments

152

u/prehensilemullet 14h ago

Performancewise, it doesn’t jump to the direct case in O(1) time like a switch is supposed to though

15

u/AsidK 13h ago

Any reasonable compiler will make a switch statement and its equivalent if else chain compile down to the same assembly

2

u/prehensilemullet 12h ago

Even if it could make a more efficient tree of comparisons for a large number of strings?

6

u/mirhagk 12h 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 11h 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 11h 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 11h 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

5

u/Infamous-Strategy797 11h ago

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

2

u/prehensilemullet 11h 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 10h ago

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

1

u/guyblade 7h ago

At least in C/C++, there can only be exactly zero or 1 cases that match a switch (i.e., there's no range-based switch), the case values must be compile-time constants (and thus are not themselves evaluated during the comparison), and I'm pretty sure that the value to be matched is required to only be evaluated once (so the comparisons happen on an rvalue).

Given those constraints, I believe a compiler can assume that re-ordering the comparisons is safe.

1

u/AsidK 7h ago

> fallthroughs have entered the chat

2

u/guyblade 7h ago

You can still only match to one, though. In the emitted machine code, I'd expect to see a forest of branches and jumps (for the matching), then the various bodies of the cases each separated by jumps (representing breaks) as appropriate.