Why switch is faster than if
Because there are special bytecodes that allow efficient switch statement evaluation when there are a lot of cases.
If implemented with IF-statements you would have a check, a jump to the next clause, a check, a jump to the next clause and so on. With switch the JVM loads the value to compare and iterates through the value table to find a match, which is faster in most cases.
A switch
statement is not always faster than an if
statement. It scales better than a long list of if-else
statements as switch
can perform a lookup based on all the values. However, for a short condition it won't be any faster and could be slower.