Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if else vs switch performance in java

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?

like image 896
Gökhan Akduğan Avatar asked Oct 10 '15 08:10

Gökhan Akduğan


2 Answers

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

like image 56
M Sach Avatar answered Sep 29 '22 13:09

M Sach


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.

like image 35
Fadils Avatar answered Sep 29 '22 13:09

Fadils