Efficiency and performance comparison between switch and ifelse in php _ PHP Tutorial

Source: Internet
Author: User
Compare the efficiency and performance of switch and ifelse in php. 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. We don't need to introduce the differences between switch and ifelse in PHP. here I will introduce you to 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:

$ 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:

$ 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 ';
}

Bytes. PHP has two sides...

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.