I read somewhere that the switch statement uses “Binary Search” or some sorting techniques to exactly choose the correct case and this increases its performance compared to else-if ladder.
And also if we give the case in order does the switch work faster? is it so? Can you add your valuable suggestions on this?
We discussed here about the same and planned to post as a question.
It’s actually up to the compiler how a
switchstatement is realized in code.However, my understanding is that when it’s suitable (that is, relatively dense cases), a jump table is used.
That would mean that something like:
Would end up getting compiled to something like (horrible pseudo-assembler, but it should be clear, I hope).
If that’s not the case, there are other possible implementations that allow for some extent of “better than a a sequence of conditionals”.