Why switch is faster than if
I have found lots of books in java saying switch statement is faster than if else statement. But I didnot find antwhere saying why switch is faster than if .
Example
I have a situation i have to choose any one item out of two i can use either of the following way
switch(item){
case BREAD:
//eat Bread
break;
default:
//leave the restaurant
}
or using if statement like the following
if(item== BREAD){
//eat Bread
}else{
//leave the restaurant
}
considering item and BREAD is constant int value
In the above example which is faster in action and why?
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.
At the bytecode level, subject variable is loaded only once into processor register from a memory address in the structured .class file loaded by Runtime,and this is in a switch statement; whereas in an if-statement, a different jvm instruction is produced by your code-compiling DE, and this requires that each variable be loaded in to registers although same variable is used as in next preceeding if-statement. If you know of coding in assembly language then this would be commonplace; although java compiled coxes are not bytecode, or direct machine code, the conditional concept hereof is still consistent. Well, I tried to avoid deeper technicality upon explaining. I hope I had made the concept clear and demystified. Thank you.
链接地址: http://www.djcxy.com/p/86588.html上一篇: 循环是否真的更快?
下一篇: 为什么开关比如果更快