Home  >  Article  >  Backend Development  >  php: Detailed explanation of the difference between switch and if

php: Detailed explanation of the difference between switch and if

黄舟
黄舟Original
2017-06-25 09:58:404429browse

【Transfer】switchThe difference between if
If you are purely comparing numbers or characters, it is recommended to use switch, because it will only take out the variable in the initial switch brackets Value once, and then compare this value with the case set below. However, if you use if, the variable value must be taken out every time you encounter the conditional expression. This is the difference in efficiency. For example:

if(a == 1) 
//... 
else
 if(a == 2) 
//... 
else if(a == 3) 
//...

In the worst case, that is, when a = 3, this program fragment requires a total of 3 comparisons, and the variable a must be taken out for each comparison. value once. If you change to switch:

switch(a) 
{ 
case 1: 
//... 
break
; 
case 2: 
//... 
break; 
case 3: 
//... 
break; 
}

In this program fragment, only take out the value of variable a in the brackets of the switch at the beginning, and then compare the following cases one by one to see the difference in efficiency Right here. Of course, it is not bad to use if. When encountering compound conditions, switch cannot help. Since complex conditional statements cannot be combined in switch, you have to use if. Simply put, if and switch can be used flexibly together.

If is very similar to switch statement, how to choose to use it? If there are not many specific values ​​to judge, and they conform to the byte, short, char, int, String types, although both statements can be used, it is recommended to use the switch statement, which is more efficient. Other situations: interval judgment, The result type is boolean for judgment, use if, if is more general.

The above is the detailed content of php: Detailed explanation of the difference between switch and if. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn