If else vs switch performance in java

I would like to know if there is a difference in efficiency between using an if or switch statement. For instance:

if(){ //code } else if(){ //code } else{ //code } 

I believe that the program should go and check all the if statements, even if the first if statement was true.

 switch(i){ case 1: //code break; case 2: //code break; 

But there is a break command in the switch. Am I right? If not, can you explain the difference in performance between the two?

+5
source share
3 answers

Switch perf is better than if else , since there will be one time in case of switching. Once he has evaluated the switch, he knows which case should be executed, but in the case of if else he must go through all the conditions in case of a worse scenario.

The longer the list condition, the better the performance of the switch will be, but for a shorter list (only two conditions) it can be slower and

From why switch faster than if

Using the switch, the JVM loads the value for comparison and iteration through the table of values ​​to find a match, which is faster in most cases

+3
source

Switch is faster.

Imagine that you are at a crossroads with many paths. Using Switch you get to the right path for the first time.

With if , you should try all the ways before finding the right one.

Use Switch when possible.

Of course, for a computer, this difference is very small that you don’t even notice. But yes, you understand.

+1
source

I think the code is perfectly clear. If if, you must check each case after each case (in the worst case, the last return returns a result). Using the switch, some type, for example, a special check of the byte code and the transition to the correct case for return. Thus, the switch is slightly faster than the if statement. However, I think we need to focus on how we implement to make reading easier. In some simple cases, if is also an option for writing code.

0
source

Source: https://habr.com/ru/post/1233405/


All Articles