40 skills to optimize your PHP code

Source: Internet
Author: User
Tags switch case
40 tips to optimize your PHP code
The English copyright belongs to Reinhold Weber, the author of Yangyang (aka Davidkoree). The bilingual version may be used for non-commercial communication, provided that the English version of the author, copyright information, and the author of the Chinese translation.


1. If a method can be static, declare it static. Speed improvement are by a factor of if a method is static, it is statically declared. The rate can be increased to 4 times times.

2. Echo is faster than print. echo is faster than print.

3. Use echo ' s multiple parameters instead of string concatenation. Use Echo's multiple arguments, which refer to a comma instead of a period, instead of a string connection.

4. Set the MaxValue for your for-loops before and not in the loop. Determine the maximum number of loops before executing the For loop, and do not calculate the maximum value once per loop.

5. Unset your variables to free memory, especially large arrays. Unregister those unused variables, especially large arrays, in order to free up memory.

6. Avoid Magic like __get, __set, __autoload try to avoid using __get,__set,__autoload.

7. Require_once () is expensive require_once () expensive.

8. Use full paths in includes and requires, less time spent on resolving the OS paths. The full path is used when the file is included, and less time is required to resolve the operating system path.

9. If you need to find out the time time of the script started executing, $_server[' request_time '] is preferred to time () Want to know when the script starts executing (that is, the server side receives the client request) the moment, uses $_server[' Request_time '] is better than time ().

See if you can use STRNCASECMP, strpbrk and Stripos instead of regex. Check if you can use the Strncasecmp,strpbrk,stripos function instead of the regular expression to accomplish the same function.

One. Str_replace is faster than preg_replace, but strtr are faster than str_replace by a factor of 4. The Str_replace function is faster than the Preg_replace function, but the efficiency of the STRTR function is four times times that of the Str_replace function.

If the function, such as String replacement function, accepts both arrays and single characters as arguments, and If y Our argument list isn't too long, consider writing a few redundant replacement statements, passing one character at a Tim E, instead of one line of code, accepts arrays as search and replace arguments. If a string replaces a function that accepts an array or character as an argument, and the parameter length is not too long, consider writing an additional replacement code so that each pass argument is a character instead of just one line of code that accepts the array as a parameter for querying and replacing.

It ' s better to use SELECT statements than multi if, else if, statements. It is better to use multiple if,else if statements using the Select Branch statement (that is, switch case).

Error suppression with @ is very slow. [Email protected]

Turn on Apache's mod_deflate open the Apache mod_deflate module.

The. Close your database connections when you ' re-done with them. The database connection should be turned off when it is finished.

$row [' ID '] is 7 times faster than $row [ID]. The efficiency of the $row [' ID '] is 7 times times that of $row[id].

Error messages is expensive. Error messages are costly.

Functions inside of for loops, such as for ($x =0; $x < count ($array); $x) the count () function gets Calle D each time. Try not to use functions in the For loop, such as for ($x =0; $x < count ($array), $x) call the count () function once per loop.

Incrementing a local variable in a method is the fastest. Nearly the same as calling a local variable in a function. Incrementing a local variable in a method is the fastest speed. is almost equivalent to the speed at which local variables are called in the function.

Incrementing a global variable is 2 times slow than a local var. incrementing a global variable is a twice-fold slower than incrementing a local variable.

Incrementing an object property (eg. $this->prop++) is 3 times slower than a local variable. Incrementing an object property, such as $this->prop++, is 3 times times slower than incrementing a local variable.

Incrementing an undefined local variable is 9-10 times slower than a pre-initialized one. Incrementing a non-predefined local variable is 9 to 10 times times slower than incrementing one of the pre-defined local variables.

Just declaring a global variable without using it in a function also slows things down (by about the same amount as in Crementing a local Var). PHP probably does a check to see if the global exists. Defining only a local variable without calling it in the function also slows down the speed (which is equivalent to incrementing a local variable). PHP will probably check to see if there are global variables.

Method invocation appears to being independent of the number of methods defined in the class because I added more meth ODS to the test class, before and after the test method, with no change in performance. The method invocation appears to be independent of the number of methods defined in the class, because I added 10 methods before and after the test method, but there was no performance change.

Methods in derived classes run faster than ones defined in the base class. A method in a derived class runs faster than the same method that is defined in the base class.

A function call with one parameter and an empty function body takes about the same time as doing 7-8 $localvar + + Opera tions. A Similar method call was of course about $localvar + + operations. Calling an empty function with one parameter takes a time equivalent to performing a local variable increment operation of 7 to 8 times. A similar method call takes a time close to 15 local variable increment operations.

Surrounding your string by ' instead of ' would make things interpret a little faster since PHP looks for variables ins IDE "..." but not inside ' ... '. Of course you can be only if you don't need to having variables in the string. Using single quotes instead of double quotation marks to contain strings can be faster. Because PHP searches for a variable in a string surrounded by double quotes, the single quotation mark does not. Of course, you can do this only if you don't need to include variables in the string.

When echoing strings it's faster to separate them by comma instead of dot. Note:this works with Echo, which is a function so can take several strings as arguments. When outputting multiple strings, it is faster to separate the strings with commas instead of periods. Note: Only echo can do this, it is a "function" that can take multiple strings as arguments (the PHP manual says that ECHO is a language structure, not a real function, so the function is enclosed in double quotes).

A PHP script would be served at least 2-10 times slower than A static HTML page by Apache. Try to use the more static HTML pages and fewer scripts. Apache Parsing a PHP script is 2 to 10 times times slower than parsing a static HTML page. Use static HTML pages as much as possible and use fewer scripts.

Your PHP Scripts is recompiled every time unless the scripts is cached. Install a PHP caching product to typically increase performance by 25-100% by removing compile times. Unless the script can be cached, it will be recompiled every time it is called. Introducing a set of PHP caching mechanisms can typically improve performance by 25% to 100% to eliminate compilation overhead.

Cache as much as possible. Use memcached-memcached are a High-performance memory object caching system intended to speed up dynamic Web applications By alleviating database load. OP code caches is useful so, your script does not has a to is compiled on every request. Try to cache and use memcached. The memcached is a high-performance memory object caching system that can be used to accelerate dynamic Web applications and reduce database load. Caching of the OP code is useful so that the script does not have to recompile for each request.

When working with strings and you need to check the the string was either of a certain length you ' d understandably wou LD want to use the strlen () function. This function is pretty quick since it's operation does not perform any calculation but merely return the already known Le Ngth of a string available in the Zval structure (internal C struct used to store variables in PHP). However because strlen () is a function it's still somewhat slow because the function call requires several operations suc H as Lowercase & Hashtable lookup followed by the execution of said function. In some instance you can improve the speed of your code by using a Isset () trick. When you manipulate a string and need to verify that its length satisfies a certain requirement, you will of course use the strlen () function. This function executes quite quickly because it does not do any calculations and only returns the length of the known string stored in the Zval structure (the built-in data structure of C for storing PHP variables). However, because strlen () is a function, it is somewhat slower, because function calls go through a number of steps, such as lowercase letters (lowercase, PHP does not differentiate between function names), and hash lookups, which follow the called functions. In some cases, you can use the isset () technique to speed up execution of your code.
Ex. (example below)
if (strlen ($foo) < 5) {echo "Foo is too Short";}
vs. (compare with the following tips)
if (!isset ($foo {5})) {echo "Foo is too Short";}
Calling Isset () happens to being faster then strlen () because unlike strlen (), Isset () are a language construct and not a Func tion meaning that it's execution does not require function lookups and lowercase. This means you has virtually no overhead on top of the actual code that determines the string ' s length. Calling Isset () happens to be faster than strlen (), because unlike the latter, Isset (), as a language structure, means that its execution does not require function lookups and lowercase letters. In other words, you're actually not spending much overhead in the top-level code that examines the length of the string.

When incrementing or decrementing the value of the variable $i + + happens to bes a tad slower then + + $i. This is something PHP specific and does don't apply to other languages, so don ' t go modifying your C or Java code thinking I T ' ll suddenly become faster, it won ' t. + + $i happens to being faster in PHP because instead of 4 opcodes used for $i + + you only need 3. Post incrementation actually causes in the creation of a temporary var that's then incremented. While pre-incrementation increases the original value directly. This is one of the optimization so opcode optimized like Zend ' s PHP optimizer. It is still a good idea to keep in mind since not all opcode optimizers perform this optimization and there are plenty of ISPs and servers running without an opcode optimizer. When the variable $i is incremented or decremented, $i + + will be slower $i than the + +. This difference is unique to PHP and does not apply to other languages, so please do not modify your C or Java code and expect them to become fast and useless. + + $i is faster because it requires only 3 instructions (opcodes), $i + + requires 4 instructions. The post increment actually produces a temporary variable, which is then incremented. The predecessor increment is incremented directly on the original value. This is one of the most optimized processing, as Zend's PHP optimizer did. It is a good idea to keep this optimization process in mind because it is notSome instruction optimizer will do the same optimization, and there are a large number of Internet service providers (ISPs) and servers that do not have an assembly instruction optimizer.

Not everything have to be OOP, often it's too much overhead, each method and object call consumes a lot of memory. Not necessarily object-oriented (OOP), object-oriented tends to be expensive, and each method and object invocation consumes a lot of memory.

Implement every data structure as a class, arrays is useful, too. Arrays are also useful not to implement all of the data structures in a class.

The PNs Don ' t split methods too much, think, which code you'll really re-use. Don't subdivide the method too much, think about what code you really want to reuse?

You can always split the code of a method later, when needed. When you need it, you can always break the code down into methods.

The countless predefined functions. Try to use a lot of PHP built-in functions.

Very time consuming functions in your code, consider writing them as C extensions. If there are a lot of time-consuming functions in your code, you might consider implementing them in C extensions.

A. Profile your code. A Profiler shows you, which parts of the your code consumes how many time. The Xdebug debugger already contains a profiler. Profiling shows you, the bottlenecks in overview. Evaluate the test (profile) of your code. The inspector will tell you what parts of the code are consuming time. The Xdebug debugger contains an inspection program that can show the bottleneck of the code in general.

Mod_gzip which is available as a Apache module compresses your data on the fly and can reduce the data to transfer up To 80%. The mod_zip can be used as an Apache module to instantly compress your data and reduce data transfer by up to 80%.

Excellent article (http://phplens.com/lens/php-book/optimizing-debugging-php.php) about optimizing PHP by John Lim Another wonderful article on optimizing PHP, written by John Lim.



  • Related Article

    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.