PHP code optimization

Source: Internet
Author: User
Tags php script switch case

Engaged in the development of PHP for many years, there are a lot of performance optimization on the development of PHP need to pay attention to, or PHP tips are can improve the performance of PHP, now will be summed up in some of the more practical ways to improve PHP performance to do a summary and share, welcome novice onlookers, high finger is!1. It is quicker to use single quotes instead of double quotes to contain strings. Because PHP searches for a variable in a string surrounded by double quotes, the single quotation mark does not, note: only echo can do this, it is a function that can take more than one string as a parameter (the PHP manual says that ECHO is the language structure, not the real function, so the function with double quotation marks).2, if the method of the class can be defined as static, as far as possible to define as static, it will increase the speed of nearly 4 times times.3. The speed of $row [' ID '] is 7 times times that of $row[id].4. Echo is faster than print, and uses Echo's multiple parameters (referring to commas instead of periods) instead of string connections, such as Echo $str 1, $str 2.5, determine the maximum number of cycles before executing the For loop, do not put the countstrlensizeof and so on every time to repeat the same things, but the result is the same thing in the condition statement for the For Loop, it is also best to use foreach instead of A For loop.6, write off those unused variables, especially large arrays, objects and so on, in order to free up memory.7, require_once () expensive, according to the test data, the use of require_once than require slower 3-4 times, the specific solution can first check whether there is a reference and then decide that you need require.8. Include and require files do not use relative paths as far as possible, because when using relative paths it will first look up the specified PHP include path and then look for the current directory, so it will check too many paths, so the best choice is to use absolute paths.9. If you want to know when the script starts executing (that is, the server side receives the client request), use $_server[' request_time '] better than time (). As for the role of $_server[' Request_time ', the document explains that the variable holds the timestamp at the beginning of the page request. Valid from PHP 5.1.0. Is the same as the time function effect.10, can use the function instead of the regular expression where possible to use the function to complete.11, the Str_replace function is faster than the Preg_replace function, but the efficiency of the STRTR function is four times times the Str_replace function. The function of the STRTR () function is to convert specific characters in a string.12, do not make unnecessary substitution, even if there is no replacement operation, using Str_replace will also allocate memory for its parameters. Very slow! Workaround: Use Strpos to find the relevant information to see if the need to replace, if necessary, and then replace. The actual efficiency comparison is: If replacement is needed: efficiency is almost equal, the difference is around 0.1%. If no replacement is required: The Strpos speed will increase by 200%.12, if a string substitution function, can accept an array or character as a parameter, and the parameter length is not too long, then you can consider an extra piece of replacement code, so that each pass argument is a character, rather than write a line of code to accept the array as the query and replace parameters.13. Using the Select Branch statement (that is, switch case) is better than using multiple if,else if statements. 14. Do not misuse the @ operator. Although @ seems simple, there are actually many operations in the background. With @ than without @, efficiency gap: 3 times times. In particular, do not use @ in loops.15, open the Apache mod_deflate module, can improve the browsing speed of the page. The Mod_deflate module provides a deflate output filter that allows the server to compress output content before it is sent to the client to conserve bandwidth. Please refer to the relevant documentation for specific settings.16, increment the local variable in the method, the speed is the quickest. is almost equivalent to the speed at which local variables are called in the function. Incrementing a global variable is twice times slower than incrementing a local variable.17. Incrementing an object property in a method (for example: $this-num++) is 3 times times slower than incrementing a local variable (for example, $num).18. Incrementing an undefined local variable is 9 to 10 times times slower than incrementing a pre-defined local variable.19. 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.20. 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.21. A method in a derived class runs faster than the same method defined in the base class.22. Call an empty function with one parameter, which takes the same amount of time as 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.23, Apache parsing a PHP script time 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.24. 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.25, try to do the cache, you can 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.26. 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, as in the following example:
PHP code copy content to clipboardif (strlen ($STR)6) {echo ' str is less than 6 characters ';}(The code example above is compared with the tips below)
PHP code copy content to clipboardif (!isset ($str {6})) {echo ' str is less than 6 characters ';}
Calling Isset () is faster than strlen () because Isset () is a language construct, meaning 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 examines the length of the string.27. When the increment or decrement of the variable $i is executed, $i + + will be slower $i than + +. 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 in mind, as not all of the instruction optimizer will do the same optimizations, and there are a large number of Internet service providers and servers that do not have an assembly instruction optimizer.28, not the object-oriented (OOP), object-oriented tends to be very expensive, each method and object calls will consume a lot of memory.29, not to use the class to implement all the data structure, arrays are also useful.30. Don't subdivide the method too much, think carefully about what code you really intend to reuse. 31. Use PHP built-in functions wherever possible with PHP built-in functions.32. If there are a lot of time-consuming functions in your code, you might consider implementing them in C extensions.33. 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.34, Mod_zip can be used as Apache module, to compress your data instantly, and to reduce the data transfer volume by 80%.35, in the case can be replaced with file_get_contents file, fopen, feof, Fgets and other series of methods, as far as possible with the file_get_contents, because his efficiency is much higher! But pay attention to file_get_ Contents PHP version problem when opening a URL file;36, as far as possible to file operations, although the PHP file operation efficiency is not low.37, optimize the Select SQL statement, unless the table field, SQL keyword try to use uppercase instead of lowercase.38. Do not declare variables in the loop, especially large variables: objects, the workaround is to pre-iterate the variables that need to be declared before looping.39, multidimensional arrays try not to loop nested assignments.40, in the case of PHP internal string manipulation function, do not use regular expressions.41, the Foreach efficiency is higher than while and for.42, replace i=i+1 with I+=1. Conform to the habit of cc++, the efficiency is high; 43, to global variables, should be used up on unset () off;44, intentionally ignore the PHP close tag (ie).45, before writing or saving the file, please ensure that the directory is writable, if not writable, output error message. This will save you a lot of debugging time. In particular, Linux system, the need to handle permissions, directory permissions are not enough to cause a lot of problems, files may not be read and so on. For example, the following:
PHP code copy content to clipboard$contents = all the content;$file _path = varwwwprojectcontent.txt;File_put_contents ($file _path, $contents);This is largely true, but there are some indirect problems that file_put_contents may fail for several reasons (1) Parent directory does not exist(2) directory exists, but not writable(3) file is written and lockedSo it's better to do a clear check before writing a file, the correct wording is as follows:
PHP code copy content to clipboardPhp$contents = ' test content ';$dir = ' Varwwwproject ';$file _path= $dir. Content.txt;if (is_writable ($dir)) {File_put_contents ($file _path, $contents);}else{Die (' directory does not exist or directory is not writable! ‘);}46, do not rely on the Submit button value to check the form submission behavior, such as the following situation:
PHP code copy content to clipboardif ($_post[' submit '] = = ' Save ') {Save the Things}Most of the above are correct, except that the application is multilingual. ' Save ' may represent other meanings, how do you differentiate them, so do not rely on the value of the Submit button. The correct wording is as follows:
PHP code copy content to clipboardif ($_server[' request_method ') = = ' POST ' and isset ($_post[' submit ')) {Save The things}47. Do not use $_session variables directlyTo give a simple example$_session[' username '] = $username; or $username = $_session[' username ');This can cause some problems, and if multiple apps are running in the same domain, the session variables may conflict, and two different apps may use the same session key, for example, a front-end portal, and a backend management system using the same domain name. For this scenario, the solution is as follows, using the application-related key and a wrapper function:
PHP code copy content to clipboardPhpDefine (' app_id ', ' abc_corp_ecommerce ');function Session_get ($key) { $k =app_id. $key;if (Isset ($_session[$k])) {return $_session[$k];}return false;}function Session_set ($key, $value) { $k =app_id. $key;$_session[$k]= $value;return true;}48. Encapsulate your tool functions in a class, if you define a number of tool functions in a file, as follows
PHP code copy content to clipboardPhpfunction Utility_a () {This function does a utility thing like string processing}function Utility_b () {This function does nother utility thing like database processing}function Utility_c () {This function is:}But the use of these functions is scattered throughout the application, so you can encapsulate them in a class
PHP code copy content to clipboardPhpClass Utility {public static function Utility_a () {} public static function Utility_b () {}public static function Utility_c () {}}Call methods such as: $a =utilityutility_a (); or $b =utilityutility_b ();The advantage of this is that if you have a function with the same name in PHP, you can avoid conflicts and maintain them fairly easily.49. Use Array_map to quickly process an array, say you want to trim all the elements in the array, the novice may:
PHP code copy content to clipboardforeach ($arr as $c = $v) {$arr [$c] = Trim ($v);}But it's easier to use array_map than the above, like
PHP code copy content to clipboard$arr = Array_map (' Trim ', $arr);This will call for the trim function for each element of the $arr array, and another similar function is Array_walk, please consult the documentation for more tips.50. Using PHP filter to verify the data, you must have used regular expressions to verify the email, IP address, etc., you can try to use the PHP built-in filter extension to complete the relevant verification and check the input.51. Make sure your scripts use a single database connection from start to finish, open the connection correctly at the beginning, use it until the end, and finally close it, like this, opening a connection in a function is very bad
PHP code copy content to clipboardPhpfunction Add_to_cart () {$db = new Database ();$db-query (INSERT into cart ...);}function Empty_cart () {$db = new Database ();$db-query (DELETE from cart ...);}The above code instance creates a database connection in two functions, which takes a large amount of time and memory, slowing down the overall speed of the application. So the database link can use the singleton mode is the best, so as to minimize the time required for database connection and the loss of performance.

PHP code optimization

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.