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?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With