PHP Performance Optimization Encyclopedia (php.ini) _php tips

Source: Internet
Author: User
Tags anonymous apc garbage collection php code strlen switch case zend zend framework

The first chapter is optimized for system calls too much
My optimization for syscall calls too many problems, so use Strace to trace Apache for analysis.

1. Apache2ctl-x &
Start the httpd process with the-X (debug) parameter, which starts only 1 httpd processes
2. Ps-ef | grep httpd
Find the PID that needs strace
3. Strace-p $PID-O/tmp/strace.log
Send an HTTP request to httpd and you can see the strace information.

first, the include_path problem

You can generally see a lot of these types of information:
Stat64 ("/error/dir/test.php", 0xbfab4b9c) =-1 enoent (No such file or directory)
Workaround:
1. In the application of PHP set include_path, remove '. ' And so on relative paths, put the directories that contain a lot of files in front of them. Ensure that the traversal of the include_path can be quickly found.
2. Use absolute path to Include,require,include_once,require_once
3. Use PHP's automatic loading mechanism

Second, Apache rewrite configuration

Copy Code code as follows:

Rewriteengine on
Rewritecond%{document_root}%{request_filename}!-f
Rewritecond%{document_root}%{request_filename}!-d
Rewriterule. *%{document_root}%/index.php
#RewriteRule. */index.php

The last commented out rewrite configuration is not good because it will be one more time per request Syscall
Stat64 ("/index.php", 0xbfab4b9c) =-1 enoent (No such file or directory)

three, Apache log problem
When we test a problem, we find that if the custom log has recorded the access time and other information, there will be a lot more
Stat64 ("/etc/localtime", {st_mode=s_ifreg|0644, st_size=165, ...}) = 0
If you log more logs, performance degradation is very serious, for simple applications, logging complex logs, performance will be reduced by 30 times times.
Workaround:
Proxy on the HTTP layer of multiple Apache front-end racks, such as Haproxy,nginx. Log in these places. The access layer load is generally not high, so proxy can do some logging work. In this configuration, you can turn off the Apache log.

Iv. Realpath () question
Everyone can look at this article: http://bugs.php.net/bug.php?id=43864
The host CPU and IO will be higher after Lstat64 calls.
The reason, because php5.2.x to Realpath () implementation is not good enough, resulting in the directory hierarchy, the gradual call Lstat64 ().
To solve this problem, it uses Realpath_cache to store its realpath for a file. Here only store the leaf node of the Realpath, and the contents of the path is not stored, so in doing "/a/b/c/d/e/f/g/a.php" Realpath check Step by step call Lstat64, and in doing "/a/b/c/d/e/f/g/b.php" Check the time, but also to "/a/b/c/d/e/f/g/" to do a stepwise inspection. So some of the optimization advice is to "reduce the directory hierarchy, even to the"/"root directory." Of course I do not recommend this. Starting from 5.3.0, PHP to Realpath () did an efficient implementation of the road Realpath the middle path has also done a cache, to the above situation as an example, check "/a/b/c/d/e/f/g/b.php" when it will only do "b.php" check. Therefore, upgrading to php5.3.0 above version can solve this problem very well.
Workaround:
1. Use include_once and require_once as little as possible
Because these two functions do realpath checking, it prevents the case of signed links from causing repeated loading. You can reduce realpath calls without them.
2. Reasonably set the realpath_cache_size and Realpath_cache_ttl parameters in php.ini
Since the use of realpath_cache, there must be a size limit. For projects that use a lot of files, such as the Zend Framework, the default realpath_cache_size=16k is too small, you need to increase this setting, the recommended setting is more than 256K. In addition the default realpath_cache_ttl=120,2 minutes are outdated, how to set to 3600 (1 hours).
It should be noted here that this realpath_cache is exclusive to every Apache process, so eat memory, can not set too large.
3. Upgrade to php5.3.x
There is nothing to say, if the application after detailed testing no problem, then recommended upgrade to the high version.

v. Use of APC
APC is able to cache php's opcode code and can generally improve performance by 30%. But the default apc.stat=1, so each request will access the PHP file needed to see if the file is updated, has decided whether to recompile PHP files. This is a very performance-intensive, recommended turn off.
Workaround:
1. Set apc.stat=0, do not need every request to access the required PHP file.
Note that every time the version changes the PHP file, you must call Apc_clear () to clear the APC cache, or your code will never take effect.
Six, smarty tuning
For the module is better, and the application of more Web sites, if the use of Smarty template system, this time will need to smarty tuning, otherwise the smarty part of the cost is very considerable. According to one experience, Smarty can account for about 10% of the overhead.
By default, Smarty determines whether the template file is recompiled by checking for updates to each template file. If the template file is more, there will be many more stat system calls, plus the context switch, the overhead will be large.
Workaround:
1. $smarty->compile_check = false;
Remove every test, but after this, each release will be the Compile_dir directory of the compiled template deleted, otherwise your template file will never be effective.
2. You can use the cache feature if possible.

Conclusion
After the above tuning, the conclusion is as follows:
1. Upgrade to php5.3.1 to open the above optimization, higher than 5.2.3 performance of more than 10%
2. In optimized configuration, a search application developed using the Zend Framework can request up to 210/rps per second
3. In optimized configuration, a search application developed using the doophp framework can request up to 450/rps per second


chapter II Using APC caching

The execution process of the PHP program
-"Client (browser) request get hello.php
--The CGI server (for example, Apache) receives a request to find a PHP handler (such as mod_php) based on the configuration.
--"Apache loading PHP handler, PHP handler read php.ini initialization PHP interpretation environment
--mod_php Locate hell.php and load it into memory
--"mod_php compiled source code into opcode tree
--"mod_php Executive opcode Tree
--"Generate results to the browser

In this process, there are several points to be noted:

1, for many code files said, especially contains a lot of include files (include or require). They need to spend more time and parse and generate intermediate code.
2, even if the PHP code file has not changed, the implementation process will be strictly followed by the process. That is, regardless of whether your program changes, each time you call, you need to recompile to generate opcode code. (This is actually the reason that the compiler cache exists)
3, this process is not only happening in the main code files, for every include and require, will carry out this process. (This can continue to be optimized)

Where can they be optimized?

1, will mod_php fast-cgi, avoid every time to load this module, this module will be to initialize each time the interpretation of PHP environment.
2, cache php file opcode code, so that, to avoid every time to compile.
APC can be used to achieve 2nd. The compilation cache removes the parsing process from executing the PHP process, so it works well for applications that contain a lot of PHP code. Generally, you can increase your speed by more than 2-3 times. For projects that contain a large number of include files, the compilation cache is more realistic about its advantages.
Note: Include is not cached by the compilation cache. For example, there are now two files: main.php and tobeinclude.php, where main.php has the statement include tobeinclude.php '. Suppose the suffix for the middle code is. OP (not really). Then add cached cache after Main.php=>main.op, Tobeinclude.php=>tobeinclude.op. But when PHP executes main.php, she still needs to parse the include command in Main.op to invoke Tobeinclude.op's content. The specific process is like this.
...=> perform main.op=> execution tobeinclude.op=>
Rather than between simple executive Main.op
So "Too many include files can degrade program performance".

the specific configuration of the APC.
Alternative PHP cache (APC) is a free and publicly optimized code cache for PHP. It is used to provide a free, open and robust architecture to cache and optimize PHP's intermediate code.
APC official website for HTTP://PECL.PHP.NET/PACKAGE/APC

1, installation
Install in PHP extension form
Phpize
./configure--ENABLE-APC--enable-apc-mmap
Make
Make install
Generate. So, copy. So to the PHP reference modules directory, modify permissions 755
2, configuration
Apc.enabled Boolean
Apc.optimization optimization
Options can be changed in the script
APC php.ini configuration Options Detailed
[APC]
; Alternative PHP cache for caching and optimizing PHP intermediate code
Apc.cache_by_default = On
; SYS
; Whether to enable buffering for all files by default.
; When set to off and used with a apc.filters instruction that starts with a plus sign, the file is cached only when the filter is matched.
APC.ENABLE_CLI = Off
; SYS
; Whether to enable the APC feature for the CLI version and open this directive only for testing and debugging purposes.
apc.enabled = On
; If APC is enabled, it is the only way to disable it if the APC is statically compiled into PHP.
Apc.file_update_protection = 2
; SYS
; When you modify a file on a running server, you should perform an atomic operation.
; That is, first write in a temporary file, and then rename the file (MV) to the final name.
; Programs such as text editors and CP, TAR, and so on, do not operate this way, resulting in the possibility of buffering the defective files.
; The default value of 2 indicates that when the file is accessed, it is not buffered if it finds that the modified time distance is less than 2 seconds.
; The unfortunate visitor may get the incomplete content, but the bad effect will not be magnified by the cache.
; If you can make sure that all of the update operations are atomic, you can turn off this feature with 0.
; If your system is slow to update due to a large number of IO operations, you need to increase this value.
Apc.filters =
; SYS
; A comma-delimited list of POSIX-extended regular expressions.
; If the source file name matches any one of the patterns, the file is not cached.
; Note that the filename used to match is the file name passed to Include/require, not the absolute path.
; If the first character of the regular expression is "+", it means that any file that matches the expression will be cached.
; If the first character is "-", no matches are cached. "-" is the default value and can be omitted.
Apc.ttl = 0
; SYS
; The number of seconds the cache entry allowed to linger in the buffer. 0 means never times out. The recommended value is 7200~36000.
; A setting of 0 means that the buffer may be filled with old cache entries, resulting in the inability to cache new entries.
Apc.user_ttl = 0
; SYS
; Similar to Apc.ttl, the recommended value is 7200~36000 for each user.
; A setting of 0 means that the buffer may be filled with old cache entries, resulting in the inability to cache new entries.
Apc.gc_ttl = 3600
; SYS
; The number of seconds the cache entry can exist in the garbage collection table.
; This value provides a security measure, even if a server process crashes while executing the cached source files.
; And the source file has been modified, and the memory allocated for the old version will not be reclaimed until this TTL value is reached.
; Setting to zero disables this attribute.
Apc.include_once_override = Off
; SYS
; Keep off, or you may cause unexpected results.
Apc.max_file_size = 1M
; SYS
; Prevents files larger than this size from being cached.
Apc.mmap_file_mask =
; SYS
; If you use –enable-mmap (default enabled) to compile Mmap support for APC,
; The value here is the Mktemp-style file mask passed to the Mmap module (the recommended value is "/TMP/APC.") XXXXXX ").
; The mask is used to determine whether the memory-mapped area is to be file-backed or shared memory backed.
; For a direct file-backed memory mapping, set to "/TMP/APC." XXXXXX "appearance (exactly 6 x).
; To use POSIX-style shm_open/mmap, you need to set it to "/apc.shm.xxxxxx."
; You can also set the "/dev/zero" to use the kernel's "/dev/zero" interface for anonymous mapped memory.
; Not defining this directive means enforcing the use of anonymous mappings.
Apc.num_files_hint = 1000
; SYS
; The approximate number of different source files that may be included or requested on the Web server (the recommended value is 1024~4096).
; If you are unsure, set to 0; This setting is primarily used for sites that have thousands of source files.
apc.optimization = 0
; Optimization level (recommended value is 0).
; A positive integer value indicates that the optimizer is enabled, and the higher the value, the more aggressive optimization is used.
; Higher values may have very limited speed increases, but are still being tested.
Apc.report_autofilter = Off
; SYS
; Whether to log all scripts that are automatically not cached due to early/late binding reasons.
Apc.shm_segments = 1
; SYS
; The number of shared memory blocks allocated for the compiler buffer (the recommended value is 1).
; If the APC runs out of shared memory and the Apc.shm_size directive is set to the maximum allowed by the system,
; You can try to increase this value.
Apc.shm_size = 30
; SYS
; The size of each shared memory block (in MB, the recommended value is 128~256).
; Some systems, including most BSD variants, have a very small default shared memory block size.
Apc.slam_defense = 0
; SYS (against using the directive, it is recommended to use the Apc.write_lock Directive)
; On a very busy server, whether you start a service or modify a file,
; can result in competitive conditions because multiple processes attempt to cache a single file at the same time.
; This directive is used to set the percentage of cache steps that the process skips when processing files that are not cached.
; For example, set to 75 means that when you encounter a file that is not cached, 75% of the probability is not cached, thereby reducing the collision probability.
; Encourage set to 0来 disable this feature.
Apc.stat = On
; SYS
; Whether to enable script update checking.
; Change this instruction value to be very careful.
; The default value on means that the APC checks whether the script is updated every time the script is requested.
; If updated, the compiled content is automatically recompiled and cached. But doing so has a detrimental effect on performance.
; If set to OFF, the performance is significantly improved by not checking.
; But for the updated content to take effect, you must restart the Web server.
; This instruction is also valid for Include/require files. But it should be noted that
; If you are using a relative path, the APC must check every time it include/require to locate the file.
; Using an absolute path allows you to skip the check, so you are encouraged to use an absolute path for include/require operations.
Apc.user_entries_hint = 100
; SYS
; Similar to the Num_files_hint directive, just for each individual user.
; If you are unsure, set to 0.
Apc.write_lock = On
; SYS
; Whether write locks are enabled.
; On a very busy server, whether you start a service or modify a file,
; can result in competitive conditions because multiple processes attempt to cache a single file at the same time.
; Enabling this directive avoids the appearance of competitive conditions.
apc.rfc1867 = Off
; SYS
; When the directive is opened, APC automatically creates a Upload_ user cache entry (the Apc_upload_progress field value) for each upload file that contains the Apc_upload_progress field just before the file field.
3. php function
Apc_cache_info-retrieves cached information (and meta-data) from APC ' s data store
Apc_clear_cache-clears the APC cache
Apc_define_constants-defines a set of constants for later retrieval and mass-definition
Apc_delete-removes a stored variable from the cache
Apc_fetch-fetch a stored variable from the cache
Apc_load_constants-loads a set of constants from the cache
Apc_sma_info-retrieves APC Shared Memory allocation information
Apc_store-cache a variable in the data store

4. Note:
APC and Apache process share memory, so only in the execution of the Apache process can be stored in the APC, the normal PHP process can not access the APC shared memory.


Chapter Three coding techniques to improve PHP performance

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.
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.
2, $row [' ID '] speed is $row[id] 7 times times.
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.
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.
5, the cancellation of those unused variables, especially large arrays, in order to free memory.
6, try to avoid the use of __get,__set,__autoload.
7, require_once () costly.
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.
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 ().
10. Functions do the same function instead of regular expressions.
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.
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.
13. Using the Select Branch statement (switch case) is better than using multiple if,else if statements.
14, using the @ block error message is very inefficient, extremely inefficient.
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.
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.
34, 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.
35, is not a matter of object-oriented (OOP), object-oriented often expensive, each method and object calls will consume a lot of memory.
36, not to use the class to implement all the data structure, the array is also useful.
37, do not subdivide the method too much, carefully think about what you really intend to reuse the code?
38, when you need, you can always break down the code into a method.
39, try to use a large number of PHP built-in functions.
40. If there are a lot of time-consuming functions in your code, you can consider using C extensions to implement them.
41, 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.
42, Mod_zip can be used as Apache module, to instantly compress your data, and to reduce the amount of data transfer by 80%.
43, 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 in opening a URL file when the PHP version problem;
44, as far as possible the file operation, although the PHP file operation efficiency is not low;
45, optimize the Select SQL statement, as far as possible in the case of INSERT, update operation;
46, as far as possible 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!) );
47, the circulation inside do not * * variable, especially large variables: objects (this seems to be not just PHP to pay attention to the problem?) );
48, multidimensional array as far as possible not to cycle nested assignment;
49, in the case of PHP internal string manipulation function, do not use regular expression;
50, foreach more efficient, as far as possible with foreach instead while and for loops;
51, the use of single quotes instead of double quotes quoted strings;
52, "Replace I=i+1 with I+=1." In line with C + + habits, efficiency is also high ";
53, 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.