PHP code optimization

Source: Internet
Author: User
Tags case statement switch case

1. Do not copy variables randomly

Sometimes in order to make the PHP code more neat, some novice PHP (including me) will copy the predefined variables into a shorter name of the variable, in fact, the result is an increase in memory consumption, will only make the program more slowly. Imagine, in the following example, if the user maliciously inserted 512KB bytes of text into the text input box, which will result in 1MB of memory consumption!


$description = $_post[' description '); Echo $description;


echo $_post[' description '];

2. Use single quotation marks for strings

The PHP engine allows the use of single and double quotes to encapsulate string variables, but this is a big difference! A string using double quotes tells the PHP engine to first read the string contents, look for the variable in it, and change the value to the variable. Generally speaking, strings are not variable, so using double quotes can cause poor performance. It is best to use a string connection instead of a double-quoted string.


$output = "This is a plain string";


$output = ' This is a plain string ';


$type = "mixed"; $output = "This is a $type string";


$type = ' mixed '; $output = ' This is a '. $type. ' String ';

3. Use the Echo function to output a string

Using the Echo () function to print out the results is easier to read, and in the next example you can see better performance.


Print ($myVariable);


Echo $myVariable;

4. Do not use connectors in Echo

Many PHP programmers (including me) do not know when to use the stench to output multiple variables, you can actually use commas to separate, instead of using strings to first connect them, as in the first example below, because the use of connectors will have a performance problem, because this will require PHP The engine first connects all the variables, then the output, and in the second example, the PHP engine outputs them sequentially.


Echo ' Hello, my name is '. $firstName. $lastName. ' and I live in '. $city;


Echo ' Hello, my name is ', $firstName, $lastName, ' and I live in ', $city;

5. Use Switch/case instead of If/else

For a single variable, using the Switch/case statement instead of the If/else statement will have better performance and the code is easier to read and maintain.


if ($_post[' action ') = = ' Add ') {AddUser ()} elseif ($_post[' action '] = = ' Delete ') {deleteuser ();} elseif ($_post[' actio n '] = = ' edit ') {Edituser ();} else {defaultaction ();}


Switch ($_post[' action ']) {case ' Add ': AddUser (), break, case ' delete ': DeleteUser (), break, Case ' edit ': Edituser (); Brea K Default:defaultaction (); Break }

1. In the file_get_contents can be used to Exchange file, fopen, feof, Fgets and other series of measures, as far as possible with the file_get_contents, because his effectiveness is much higher! But to pay attention to file_get_ Contents the PHP version of the hour when opening a URL file;
2. As far as possible to file manipulation, although PHP file manipulation effectiveness is not low;
3. Optimize the Select SQL statement, as much as possible under the image of the INSERT, update manipulation (on, I was bad);
4. Use PHP intrinsics as much as possible (but I'm trying to find a function that doesn't exist in PHP, wasting the time you can write a custom function, the experience topic!);
5. Do not declare variables in samsara, especially large variables: objects (This is not just a topic in PHP that you should pay attention to?). );
6. Multi-dimensional arrays try not to set the value of samsara nesting;
7. Do not use regular expressions when you can manipulate functions with PHP internal strings;
8.foreach is more efficient, use foreach Replace while and for Samsara as much as possible;
9. Use single quotation marks to swap double quotation marks for reference strings;
10. "Replace I=i+1 with I+=1. The habit of the appropriate C + +, the effectiveness is high ";
11. For global variables, you should run out of unset ()
12. In multiple nesting cycles, if possible, the longest cycle should be placed in the inner layer, the shortest cycle in the outer layers, so that the CPU can cut the number of cycles across the cycle, so as to optimize the function.
40 tips to optimize your PHP code
1. If a method is static, make a static declaration of it. Speed can be promoted to 4 times times.
2. Echo is faster than print.
3. Use Echo's multiple parameters (meaning: a comma instead of a period) Replace string connection.
4. Determine the maximum number of cycles before performing a for cycle, and do not draw the maximum value once per cycle.
5. The non-perishable variables, especially large arrays, are published in order to release memory.
6. Try to avoid applying __get,__set,__autoload.
7. Require_once () is expensive.
8. Apply a full path when the file is included, and less time is required to parse the operating system path.
9. If you want to know when the script starts to perform (the client pleading on the server side), apply ¥_server[' Request_time ""] better than Time ().
10. Check whether the Strncasecmp,strpbrk,stripos function can be used replace regular expression to complete the same function.
The Str_replace function is faster than the Preg_replace function, but the STRTR function is four times times more effective than the Str_replace function.
12. If a string exchange function, can take over the array or character as a parameter, and the parameter length is not too long, then you can scrutinize the additional write a swap code, so that each pass argument is a character, rather than write a line of code to take over the array as a query and exchange parameters.
13. Apply the Select Branch statement (that is, switch case) better than applying multiple if,else if statements.
14. Using the @ Barriers error message is inefficient.
15. Open the Apache mod_deflate module.
16. The database connection should be turned off when the application is complete.
17.¥row[' ID ' "] is 7 times times the potency of ¥row[id].
18. Error messages are expensive.
19. Try not to apply functions in the for samsara, such as for (¥x=0; ¥x < count (¥array); ¥X) calls the count () function once per cycle.
20. Increase the local variable in the method, the speed is the fastest. is almost equivalent to the speed at which local variables are called in the function.
21. Incrementing a global variable is twice times slower than incrementing a local variable.
22. Incrementing an object property (such as: ¥this->prop++) is 3 times times slower than incrementing a local variable.
23. Incrementing a non-predefined local variable is 9 to 10 times times slower than incrementing one of the pre-defined local variables.
24. Defining only one local variable without calling it in the function also slows down the speed (which is equivalent to incrementing a local variable). PHP may check to see if there are global variables.
25. The method invocation appears to be independent of the number of methods defined in the class, since I have added 10 methods (before and after the test method), but the function has not changed.
26. The method in the derived class runs faster than the same method defined in the base class.
27. Call an empty function with one parameter, which is equivalent to performing a local variable increment manipulation of 7 to 8 times. A similar method calls the local variable increment manipulation that takes close to 15 times.
28. It is quicker to use single quotes replace double quotes to contain strings. Because PHP searches for a variable in a double-enclosed string, the single quotation mark does not. Of course, you can do this only if you don't need to include variables in the string.
29. When outputting multiple strings, it is faster to separate the strings with a comma replace period. Attention: only echo can do this, it is a "function" that can count multiple strings as arguments (the PHP manual says that echo is a speech layout, not a real function, so add a double quote to the function).
Apache parses a PHP script 2 to 10 times times slower than parsing a static HTML page. Use static HTML pages as much as possible, rarely used scripts.
31. Unless the script can be cached, it is compiled from the beginning of each call. A set of PHP caching mechanisms can be used to promote 25% to 100% of the function to eliminate compilation overhead.
32. Try to do the cache, can apply memcached. Memcached is a high-performance memory object caching system that can be used to speed up dynamic Web applications and reduce database load. The caching of the OP code is effective, so that the script does not have to be compiled from scratch for each pleading.
33. When manipulating a string and having to check if its length satisfies a request, you will of course apply the strlen () function. This function performs quite quickly because it does not make any plan, only returns the length of the known string stored in the Zval layout (C's built-in data layout, which is used to store PHP variables). But, because strlen () is a function, more than a little bit slow, because the function call will go through a lot of steps, such as the letter lowercase (words: lowercase, PHP does not distinguish function name case), hash lookup, will follow the function of the call to perform. In some scenarios, you can apply isset () skills to speed up the fulfillment of your code.
Ex. (example below)
if (strlen (¥foo) < 5) {echo "Foo is too Short";}
vs. (struggle with the following skills)
if (!isset (¥foo{5})) {echo "Foo is too Short";}
Calling Isset () happens to be faster than strlen () because, unlike the latter, Isset (), as a speaking layout, means that it does not require function lookups and lowercase letters. In other words, you're actually not spending much overhead in the top-level code that checks the length of the string.
34. When the performance variable ¥i increment or decrement, the ¥i++ will be slower than ++¥i. This difference is unique to PHP and is not useful for other words, so please do not correct your C or Java code and expect them to become fast and useless. ++¥i is faster because it requires only 3 instructions (opcodes), and ¥i++ requires 4 instructions. The post increment actually produces a tentative variable, which is then incremented. The predecessor increment is incremented directly on the original value. This is one of the most optimized processing penalties, as Zend's PHP optimizer did. It is a good idea to remember this optimization penalty because not all of the instruction optimizer does the same optimization processing penalty, and there are many Internet service providers (ISPs) and handlers that do not have the command optimizer installed.
35. Not necessarily object-oriented (OOP), object-oriented is often expensive, and each method and object invocation consumes a lot of memory.
36. Not all data layouts are implemented with classes, and arrays are effective.
37. Don't subdivide the method too much, think carefully about what code you are really trying to reuse?
38. When you need to, you can always differentiate the code into a method.
39. Try to take a multi-volume PHP built-in function.
40. If there are many time-consuming functions in the code, you can use the C-enlarged format to implement them.
41. Evaluate your code for verification (profile). The inspector will tell you which project groups of code spend a dash of time. The Xdebug debugger contains the inspection code, which evaluates the overall display of the bottleneck.
The mod_zip can be used as an Apache module to instantly tighten your data and allow data transfer to land 80%.

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