We don't need to introduce the differences between switch and ifelse. Here I will introduce the performance of switch and ifelse. When will it be more suitable for using switch or ifelse.
Two methods in PHP are used to determine whether the value meets the conditions. If the value meets/does not meet the conditions, different actions are performed.
No matter what language programs are written, the code running efficiency will be taken into account. After reading some materials, switch and ifelse have different efficiency advantages in different 'environment.
1. When the determined value is a constant (fixed value), the switch operation efficiency is higher than the ifelse operation efficiency;
The Code is as follows: |
Copy code |
$ Changliang = 3; // The variable judgment value is a constant. Switch ($ changliang ){ Case 1: Echo 'constant value: 1 '; Break; // skip Loop Case 2: Echo 'constant value: 2 '; Break; Case 3: Echo 'constant value: 3 '; Break; } |
2. When the determined value is a variable, ifelse runs more efficiently than switch. ifelse implements the final judgment policy and starts to judge from the first condition until the last else, therefore, it is advantageous to learn to use a switch;
The Code is as follows: |
Copy code |
$ A = $ _ GET ['a']; // get the value after passing the value through GET; the value to be judged If ($ a = 1 ){ Echo 'the value of variable a is 1 '; } Elseif ($ a = 2 ){ Echo 'the value of variable a is 2 '; } Elseif ($ a = 3 ){ Echo 'the value of variable a is 3 '; } Else { Echo 'the value of variable a is unknown '; } |