I already knew that switch statements were faster (and already knew that if its like three items the performance difference isn’t worth sweating it), but I hadn’t seen what is going on behind the scenes that makes them faster.
To be clear, switch statements and if-else are not the same thing. Switch statements are forward-looking operations instead of branching logic, and they need to account for all possibilities.
When there are a lot of choices to work with, if-else statements end up working a bit like a loop, where the program has to look through all possible choices, one at a time, until it finds the one it wants to execute. However, behind the scenes, switch statements do some math wizardry to convert the conditions into pointers towards into the case we actually want to use, avoiding the sequential comparison of each condition.
The challenge going forward then is keeping an eye on how a program is being structured in order to take advantage of this performance improvement. Again, if it’s a few choices, who cares, or if if-else has readability advantages or fits the logic better, use them. But when there are many choices, or if this a bit of logic that will be used many, many times, can it be purpose built to use switch instead?
Leave a comment