Introduction to PHP performance optimization _php Tips

Source: Internet
Author: User
Tags lowercase memcached php script switch case server memory
PHP Optimization for PHP optimization is mainly related to the main parameters of php.ini adjustment and settings, the following we will look at some of the php.ini in the performance of the larger parameters should be set.
# Vi/etc/php.ini
(1) PHP function disabled find:
Disable_functions =
This option can set which PHP functions are prohibited, PHP has some functions of the risk is quite large, you can directly execute some system-level script commands, if you allow these functions to execute, when the PHP program has a loophole, the loss is very serious! Here we give the recommended disabling function settings:
Disable_functions = Phpinfo,passthru,exec,system,popen,chroot,escapeshellcmd,escapeshellarg,shell_exec,proc_open , Proc_get_statusNote: If your server contains some system state detection PHP programs, do not disable functions such as Shell_exec,proc_open,proc_get_status.

(2) PHP script execution time found:
Max_execution_time = 30
This option sets the maximum execution time for the PHP program, and if a PHP script is requested and the PHP script is not completed within the max_execution_time time, PHP does not continue to execute, returning the timeout error directly to the client. No special needs This option keeps the default setting for 30 seconds, and you can increase the time setting appropriately if your PHP script does require a long execution time.

(3) PHP script processing memory footprint found:
Memory_limit = 8M
This option specifies the maximum memory that can be consumed by the PHP script processing, the default is 8MB, and if your server memory is more than 1GB, this option can be set to 12MB for faster PHP script processing efficiency.

(4) PHP global function declaration found:
Register_globals = Off
Many articles on the web about PHP settings recommend that this option be set to ON, which is a dangerous way to set up, and is likely to cause serious security problems. If there is no special need, it is strongly recommended to keep the default settings!

(5) PHP upload file size limit found:
Upload_max_filesize = 2M
This option sets the maximum upload file size that PHP can allow, and the default is 2MB. Depending on the actual application requirements, you can increase this setting appropriately.

(6) Session storage media found:
Session.save_path
If your PHP program uses the session dialog, you can set the sessions storage location to/DEV/SHM,/DEV/SHM is the Linux system unique TMPFS file system, is the memory as the main storage mode of the file system, more excellent than the RAMDisk, Because Diskswap can be used as a supplement, and the system is self-contained modules, do not need to be configured separately. Think about how fast it will be from disk IO operations to memory operations? Just be aware that the data stored in the/DEV/SHM will be lost when the server restarts. But this is insignificant for the session.

Because the level is limited, some still do not quite understand why. If you have a better suggestion, please feel free to add!

0. It is quicker to use single quotes instead of double quotes to contain strings. Because PHP searches for variables in a string enclosed in double quotes, single quotes are not, note: only echo can do this, it is a "function" that can take multiple strings as arguments: ECHO is the language structure, not the real function, so the function is added double quotes.
PS: In single quotes, PHP does not automatically search for variables, escape characters, etc., so the efficiency is much faster. in general, strings are not variable, so using double quotes can lead to poor performance.

1, if you can define the method of the class as static, as far as possible to define static, it will increase the speed of nearly 4 times times.
PS: In fact, the speed of function, method, and static method is not much different .

2, $row [' ID '] speed is $row[id] 7 times times.
PS: Do not understand, seemingly differences only the latter will first determine whether the ID of the macro exists, if it does not exist automatically converted to a string.

3, ECHO is faster than print, and uses Echo's multiple arguments (to refer to a comma rather than a period) instead of a string connection, such as Echo $str 1, $str 2.

PS: If you use echo $str 1. $str 2 You will need the PHP engine to first connect all the variables and then the output, and echo $str 1, $str the 2,php engine will output them sequentially .

4, before executing the For loop to determine the maximum number of loops, do not calculate the maximum value per cycle, preferably using foreach instead.
PS: Operations such as Count and strlen are actually O (1), so they do not cause too much consumption, but it is a good strategy to avoid calculating each loop. It is better to use foreach instead of For, which is more efficient, and you can use a reference such as foreach ($array as & $var) If you take into account the consumption of each copy of foreach ($array as $var).

5, the cancellation of those unused variables, especially large arrays, in order to free memory.
PS: If not mistaken, unset ($array) will not immediately release memory, but it is a good habit to release at any time.

6, try to avoid the use of __get,__set,__autoload.

7, require_once () costly.
Ps:require_once and include_once need to be weighed, so the efficiency is low, but after the 5.2 version of the efficiency problem has been basically resolved.

8, include files as far as possible using the absolute path, because it avoids the PHP to include_path to find the file speed, parsing the operating system path requires less time.
PS: Support, as little as possible with Iniset () to set the include_path.

9, if you want to know the script to start execution (that is, the server to receive client requests) at the moment, using $_server[' request_time ' is better than time ().
ps:$_server[' Request_time ' saves the timestamp at which the request was initiated, while time () returns the UNIX timestamp for the current time.

10. Functions do the same function instead of regular expressions.
PS: This function refers to Strtok, Strstr, Strpos, Str_replace, substr, explode, implode, and so on.

11, 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.
PS: String operations are faster than regular substitutions.

12. If a string substitution function can accept an array or character as a parameter, and the parameter length is not too long, consider writing an extra paragraph of substitution code so that each pass parameter is a character, rather than writing a single line of code to accept the array as a query and replacement parameter.
PS: You need to consider the overhead difference between built-in functions and user-defined functions, and I'm afraid this is not worth it.

13. Using the Select Branch statement (switch case) is better than using multiple if,else if statements.
The switch in ps:php supports numeric and string variables, which are more useful than the C switch, and are recommended for use.

14, using the @ block error message is very inefficient, extremely inefficient.
PS: Is there any alternative? No words still have to use ...

15, open the Apache mod_deflate module, you can improve the browsing speed of the Web page.

16, the database connection should be turned off when use is finished, do not use long connection.
PS: Before connecting, it is best to set the appropriate time-out mechanism, such as link timeout, read-write timeout, wait timeout, etc.

17. Error messages are costly.

18, in the method to increase the local variable, speed is the fastest. Almost as fast as calling a local variable in a function.

19, incrementing a global variable is twice times slower than incrementing a local variable.

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

21. Incrementing an undefined local variable is 9 to 10 times times slower than incrementing a predefined local variable.

22. Defining only one local variable instead of calling it in a function also slows down the speed (which is equivalent to incrementing a local variable). PHP will probably check to see if there are any global variables.

23. The method call appears to have nothing to do with the number of methods defined in the class, because I added 10 methods (both before and after the test method), but there was no change in performance.

24. Methods in a derived class run faster than the same method defined in the base class.

25. Call an empty function with one parameter, which takes as much time as 7 to 8 local variable increment operations. A similar method invocation takes approximately 15 times of local variable increments.

26, the time of 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 less scripting.

27. Unless the script can be cached, it will be recompiled every time it is invoked. The introduction of a set of PHP caching mechanisms typically increases performance from 25% to 100% to exempt compilation overhead.

28, try to do the cache, you can use memcached. Memcached is a high-performance memory object caching system that can be used to speed up dynamic Web applications and reduce database load. It is useful to cache the operation Code (OP code) so that the script does not have to recompile for each request.

29. When manipulating strings and having to check whether their lengths meet certain requirements, you will of course use the strlen () function. This function executes fairly quickly because it does not do any calculations and returns only the known string lengths stored in the Zval structure (c's built-in data structure for storing PHP variables). However, since strlen () is a function, it will be somewhat slower, because function calls go through a number of steps, such as lowercase letters, PHP is case-insensitive, and hash lookups follow the functions that are called. In some cases, you can use the isset () technique to speed up the execution of your code.
(Examples below)
if (strlen ($foo) < 5) {echo "Foo is too Short" $$}
(compare with the following tips)
if (!isset ($foo {5})) {echo "Foo is too Short" $$}
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 lookup and lowercase. That is, you're actually not spending too much on the top-level code that verifies the length of the string.
PS: Long Insight.

30, when the execution variable $i increment or decrement, $i + + will be slower than the + + $i. This difference is specific to PHP and does not apply to other languages, so please do not modify your C or Java code and expect them to quickly become useless. + + $i faster because it requires only 3 instructions (opcodes), $i + + requires 4 instructions. A post increment actually produces a temporary variable, which is then incremented. And the predecessor increment increases directly on the original value. This is one of the most optimized processes, as Zend's PHP optimizer has done. Keeping this optimization in mind is a good idea, because not all command optimizer will do the same optimization, and there are a large number of Internet service providers (ISPs) and servers that do not have assembly instruction optimizer.

31, is not a matter of object-oriented (OOP), object-oriented often expensive, each method and object calls will consume a lot of memory.

32, not to use the class to implement all the data structure, the array is also useful.

33, do not subdivide the method too much, carefully think about what you really intend to reuse the code?

34, when you need, you can always break down the code into a method.
PS: Decomposition into a proper method, the number of lines using a high frequency of the method to write code as far as possible, can reduce the function stack cost, and the method of nesting should not be too deep, otherwise greatly affect the operation of PHP efficiency.

35, try to use a large number of PHP built-in functions.

36. If there are a lot of time-consuming functions in your code, you can consider using C extensions to implement them.

37, evaluate the test (profile) your code. The inspector will tell you which parts of the code are consuming much of the time. The Xdebug debugger includes a test procedure that can be used to show code bottlenecks in general.

38, Mod_zip can be used as Apache module, to instantly compress your data, and to reduce the amount of data transfer by 80%.

39, can use file_get_contents instead of file, fopen, feof, Fgets, and other series of methods, as far as possible with file_get_contents, because his efficiency is much higher! But pay attention to file_get_ Contents PHP version problem when opening a URL file;
PS: Remember this, try to use file_get_contents and file_put_contents, do not need to determine whether the file handle open successfully.

40, as far as possible the file operation, although the PHP file operation efficiency is not low;

41, optimize the Select SQL statements, as far as possible, as little as possible insert, update operation (in update, I was a bad batch);

42, as far as possible the use of PHP internal functions (but I was in order to find a PHP does not exist in the function, wasted the time to write a custom function, experience problems ah!);
PS: Built-in functions are nearly an order of magnitude more efficient than user-defined functions.

43. Do not declare variables inside the loop, especially large variables: objects (this seems to be not just a matter of note in PHP?);
PS: This must be, too many variables or too large, the cost of each redistribution can not be ignored.

44, multidimensional array as far as possible not to cycle nested assignment;

45, in the case of PHP internal string manipulation function, do not use regular expression;

46, foreach more efficient, as far as possible with foreach instead while and for loops;

47, the use of single quotes instead of double quotes quoted strings;
PS: Halo, this is not the first one?

48, "Replace I=i+1 with I+=1." In line with C + + habits, efficiency is also high ";

49, to global variables, should be used up on the unset () off;

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.