问题
I'd like to know if there is any efficiency difference between using if statement or switch. For example:
if(){
//code
}
else if(){
//code
}
else{
//code
}
I believe that program needs to go and check all of the if statement even if the first if statement was true.
switch(i){
case 1:
//code
break;
case 2:
//code
break;
But in the switch, there is a break command. Is my approaching right? If not, could you explain the efficiency difference between them?
回答1:
Switch
perf is better than if else
as in case of switch there will be one time evaluation . Once it evaluated the switch it knows which case needs to be executed but in case of if else
it has to go through all conditions in case of worst scenario.
The longer the list condition, better will be switch performance but for shorter list (just two conditions), it can be slower also
From Why switch is faster than if
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
回答2:
Switch
is faster.
Imagine you are at an intersection, with many paths.
With switch
, you go to the right path at the first time.
With if
, then you have to try all the paths before you find the right one.
Use switch
whenever possible.
Of course, for computer this difference is very small that you don't even notice. But yeah, you get the point.
回答3:
I think the code is quite clear. With if, you have to check each case and after case by case (in the worst case, last return gives back the result). With switch, some kind like a special byte code checking and jump to the correct case to return. So the switch is a bit faster than the if statement. However, I think we need to focus on the way we implement for easier to read. In some simple case, the if is also a choice to write code.
来源:https://stackoverflow.com/questions/33051931/if-else-vs-switch-performance-in-java