The difference between switch and if else

What is the difference between these two statements that are both conditional judgments? Let's discuss them today.

basic sentence

Code deconstruction of if else:

//单if语句,满足该条件时执行,不关心不满足的情况if(true){
   
     do something;}
//if else语句,满足该条件时执行,对不满足的情况进行对应处理if(true){
   
     do something;}else{
   
     do other things;}
// 多if语句,依次执行每一条if语句,//满足条件时执行,不满足则进行下一条if的判断。if(case1){
   
     语句一}else if(case2){
   
     语句二}else if(case3){
   
     语句三}

The code deconstruction of swich:​​​​​​​​

switch(choose){
   
     case 1:    语句一    break;  case 2:    语句二    break;  case 3:    语句三    break;  default:    默认语句}

From the perspective of grammatical structure, switch is similar to multiple if statements. In the process of writing code, many people prefer to use if else, because it is more convenient and faster to write than switch.

Execution efficiency of switch and if else

In most cases, the execution efficiency of switch is higher than that of if statement.

The reason is: when the switch statement is running, it will first generate a "jump table" to indicate the address of the actual case branch, and the index number of this "jump table" is equal to the case value in swtich. In this case, Switch does not need to traverse all conditions until it finds the correct condition like if else, but only needs to access the table entry corresponding to the index number to achieve the purpose of locating the branch.

To put it simply, switch will generate a data statistics table, count all the values ​​behind the case, and compare the data in the table when matching, if there is, it will directly jump to the corresponding case statement; if not, it will directly jump to the default statement.

What about if else?

The if else statement needs to judge the value range one by one until the correct option position is found, which will inevitably waste a lot of time.

Therefore, from the perspective of its operating efficiency, the time complexity of if else is O(n), that is, in the worst case, judge n times, the time complexity of switch is O(1), and the switch statement is even better. .

Summarize

To sum it up briefly:

1. The switch statement has a higher execution efficiency due to its unique case value judgment method, while the if else statement has a slightly slower efficiency due to the judgment mechanism.

2. Which selection statement to use is related to the current code environment. If it is a range value , it is faster to use the if else statement; if it is a certain value , it is a good choice to use switch.

Guess you like

Origin blog.csdn.net/weixin_49707375/article/details/128220943