How to optimize PHP code

Source: Internet
Author: User
The purpose of PHP code optimization is to improve the efficiency of PHP program execution, when writing PHP code, you can start from the following aspects of optimization:

1. Use single quotes instead of double quotes to include strings

2. If you can define a method of a class as static, try to define it as static, and it will rise almost 4 times times faster.

3. Better efficiency with echo instead of print

4. Timely write-off of unused variables, especially large arrays, to free up memory

5. try to avoid using __get (), __set (), __autoload ( )

6. require_once () is expensive and uses as little as possible

7. Use functions instead of regular expressions to accomplish the same function

8. Str_replace function is faster than preg_replace function

9. Using a branch statement (that is, a switch case) is better than using multiple if,else if statements

It is very inefficient to mask error messages with @

One by one. When the increment or decrement of the variable $i is executed, the + + $i is faster than the $i + +

12. Use PHP's built-in functions as much as possible

do not declare variables inside the loop body, especially large variables

. foreach is more efficient, instead of while and for loops, use foreach as much as possible

use $i +=1 instead of $i = $i +1 for higher efficiency

16. For global variables, immediately unset () off after use

17. Do some cache processing appropriately


The above describes the PHP code optimization methods, including the aspects of the content, I hope that the PHP tutorial interested in a friend helpful.

  • 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.