PHP performance optimization Daquan (php. ini), performance optimization php. ini_PHP tutorial

Source: Internet
Author: User
Tags apc apache log
PHP performance optimization Daquan (php. ini), performance optimization php. ini. PHP performance optimization (php. ini), performance optimization php. chapter 1 of ini is aimed at optimizing too many system calls. my optimization is aimed at too many syscall calls, so we use strace to track apac PHP performance optimization (php. ini), performance optimization php. ini

Chapter 1 optimization of excessive system calls
My optimization aimed at too many syscall calls, so I used strace to track apache for analysis.

1. apache2ctl-X &
Use the-X (debug) parameter to start the httpd process. at this time, only one httpd process is started.
2. ps-ef | grep httpd
Find the pid that requires strace
3. strace-p $ PID-o/tmp/strace. log
Send an http request to httpd to view the strace information.

I. include_path

Generally, we can see a lot of such information:
Stat64 ("/error/dir/test. php", 0xbfab4b9c) =-1 ENOENT (No such file or directory)
Solution:
1. set include_path in the application php, remove relative paths such as '.', and put the directories that contain a large number of files in front. Make sure that you can quickly find them when traversing include_path.
2. use absolute paths for include, require, include_once, require_once
3. use php's automatic loading mechanism

II. apache rewrite configuration

The code is 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 have more than one syscall request
Stat64 ("/index. php", 0xbfab4b9c) =-1 ENOENT (No such file or directory)

III. apache log problems
When we test a problem, we find that if the user-defined log records access time and other information, there will be a lot more
Stat64 ("/etc/localtime", {st_mode = S_IFREG | 0644, st_size = 165,...}) = 0
If a large number of logs are recorded, the performance degradation is very serious. for simple applications, the performance of complex logs is reduced by 30 times.
Solution:
Configure the http-layer proxy on multiple apache front-ends, such as haproxy and nginx. Logs are recorded in these locations. The load on the access layer is generally not high, so the proxy can record logs. In this configuration, you can disable apache logs.

IV. realpath () problems
You can take a look at this article: http://bugs.php.net/bug.php? Id = 43864
When lstat64 is used up, the CPU and I/O of the host are both high.
The reason is that the implementation of realpath () in php5.2.x is not good enough, so lstat64 () is called step by step for the directory hierarchy ().
To solve this problem, it uses realpath_cache to store its realpath for a file. Only the realpath of the leaf node is stored here, but the content on the path is not stored, so "/a/B/c/d/e/f/g/. php "calls lstat64 step by step during realpath check, while"/a/B/c/d/e/f/g/B. php "checks"/a/B/c/d/e/f/g. Therefore, some optimization suggestions are to "reduce the directory hierarchy, or even put it under the"/"Root Directory ". Of course, I do not recommend this. Starting from 5.3.0, php has implemented an efficient implementation of realpath () and cached the intermediate path of realpath, check "/a/B/c/d/e/f/g/B. php "only performs" B. php "check. Therefore, upgrading to php5.3.0 or later can solve this problem well.
Solution:
1. use include_once and require_once as little as possible
These two functions perform realpath check to prevent repeated loading due to signed links. You can reduce realpath calls without using them.
2. set the realpath_cache_size and realpath_cache_ttl parameters in php. ini reasonably.
Since realpath_cache is used, there must be a size limit. For a project that uses many files, such as Zend Framework, the default realpath_cache_size = 16 k may be too small. to increase this setting, we recommend setting it to K or more. In addition, the default realpath_cache_ttl = 3600, 2 minutes out of date, how to set to (1 hour ).
Note that this realpath_cache is exclusive to every apache process, so it is very memory-consuming and cannot be set too large.
3. upgrade php5.3.x
There is nothing to say. if the application is tested in detail and there is no problem, we recommend that you upgrade it to a later version.

5. Use of APC
Apc can cache php opcode code and improve the performance by 30%. However, the default value is apc. stat = 1. in this way, each request accesses the php file to check whether the file is updated and whether to re-compile the php file. This is very performance-consuming. we recommend that you disable it.
Solution:
1. set apc. stat to 0. you do not have to access the required php file every time you request it.
Note that every time you change the php file, you must call apc_clear () to clear the apc cache. Otherwise, your code will never take effect.
6. smarty optimization
If the smarty template system is used for websites with good modularization and many applications, you need to optimize the smarty. Otherwise, the cost of the smarty part will be considerable. Previously, based on an experience, smarty may account for about 10% of the overhead.
By default, smarty checks whether each template file is updated and determines whether to re-compile the template file. If there are many template files, there will be more stat system calls, and the overhead will not be small with context switch.
Solution:
1. $ smarty-> compile_check = false;
Remove each check, but after that, delete the compiled template of the compile_dir directory for each release. Otherwise, your template file will never take effect.
2. if possible, you can use the cache function.

Conclusion
After the above optimization, the conclusion is as follows:
1. upgrade php5.3.1 to enable the above optimization, which is 10% higher than 5.2.3.
2. in the optimized configuration, a search application developed using Zend Framework can request up to 210/rps per second.
3. in the optimized configuration, a search application developed using the doophp framework can request up to 450/rps per second.


Chapter 2 use APC cache

Php program execution process
-Client (browser) request Get hello. php
-- Cgi server (for example, apache) receives the request and searches for php processing programs (such as mod_php) based on the configuration)
-- Apache loads the php processing program, and the php processing program reads the php. ini file to initialize the php interpretation environment.
-- Mod_php: find hell. php and load it into the memory.
-- Mod_php compile the source code into the opcode tree
-- Execute opcode tree in mod_php
-- Generate the result to the browser

Note the following points in the process:

1. for many code files, especially include or require ). They need to spend more time and parse and generate intermediate code.
2. even if the PHP code file does not change, the execution process will strictly follow the process. That is to say, no matter whether your program is changed or not, you need to re-compile the opcode every time you call it. (In fact, this is the reason for the existence of the compilation cache)
3. this process occurs not only in the main code file, but also in every include and require process. (This can be further optimized)

Which areas can be optimized?

1. convert mod_php fast-cgi to avoid loading this module every time. This module also initializes the php interpretation environment every time.
2. cache the opcode of the PHP file. in this way, you can avoid compiling every time.
APC can be used for 2nd points. The compilation cache removes the parsing process during PHP execution, so it is very effective for applications that contain a large amount of PHP code. Generally, the speed can be increased by more than 2-3 times. For projects that contain a large number of include files, the compilation cache shows its superiority.
Note: include will not be compiled and cached. For example, there are two files: main. php and tobeInclude. php. among them, main. php has such a statement include tobeInclude. php '. Assume that the suffix of the intermediate code is. op (in fact, this is not the case ). After the cache is added, main. php => main. op, tobeInclude. php => tobeInclude. op. However, when executing main. PHP, php still needs to parse the include command in main. op and call the content of tobeInclude. op. The specific process is as follows.
... => Execute main. op => execute tobeInclude. op =>...
Instead of simply executing main. op.
Therefore, "too many include files will reduce program performance ".

The specific configuration of APC.
Alternative PHP Cache (APC) is a free and public PHP optimized code Cache. It is used to provide free, public, and robust architectures to cache and optimize PHP intermediate code.
Official APC website for http://pecl.php.net/package/apc

1. Installation
Install in PHP extension format
Phpize
./Configure -- enable-apc-mmap
Make
Make install
Generate. so, Copy. so to the directory where php references modules, and modify the permission 755
2. configuration
Apc. enabled boolean
Apc. optimization
The options can be changed in the script.
Apc php. ini configuration options
[APC]
; Alternative PHP Cache for caching and optimizing PHP intermediate code
Apc. cache_by_default = On
; SYS
Whether to enable caching for all files by default.
If it is set to Off and used together with the apc. filters command starting with the plus sign, the file is cached only when the filter is matched.
Apc. enable_cli = Off
; SYS
Whether to enable the APC function for the CLI version. This command is enabled only for testing and debugging purposes.
Apc. enabled = On
Whether to enable APC. if APC is statically compiled into PHP and you want to disable it, this is the only way.
Apc. file_update_protection = 2
; SYS
When you modify a file on a running server, you should perform atomic operations.
That is, first write a temporary file, and then rename the file (mv) to the final name.
The text editor, cp, tar, and other programs do not perform this operation, which may buffer incomplete files.
The default value is 2, indicating that the file is not buffered if the modification time is found to be less than 2 seconds away from the access time.
The unfortunate visitor may get incomplete content, but this bad effect will not be extended through the cache.
If you can ensure that all update operations are atomic operations, you can disable this feature with 0.
; If your system updates slowly due to a large number of IO operations, you need to increase this value.
Apc. filters =
; SYS
; A list of POSIX extension regular expressions separated by commas.
If the source file name matches any mode, the file is not cached.
Note: the file name used for matching is the file name passed to include/require, rather than 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 match will be cached. "-" Is the default value, which can be omitted.
Apc. ttl = 0
; SYS
The number of seconds that cache entries can stay in the buffer. 0 indicates never timeout. Recommended value: 7200 ~ 36000.
If it is set to 0, 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 ~ for each user ~ 36000.
If it is set to 0, 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 that cache entries can exist in the garbage collection table.
This value provides a security measure, even if a server process crashes when the cached source file is executed,
And the source file has been modified, and the memory allocated for the old version will not be recycled until the TTL value is reached.
If it is set to zero, this feature is disabled.
Apc. include_once_override = Off
; SYS
; Keep it Off. otherwise, unexpected results may occur.
Apc. max_file_size = 1 M
; SYS
; Files larger than this size cannot be cached.
Apc. mmap_file_mask =
; SYS
If you use-enable-mmap (enabled by default) to compile MMAP support for APC,
The value here is the mktemp file mask passed to the mmap module (recommended value: "/tmp/apc. XXXXXX ").
The mask is used to determine whether the memory ing area is file-backed or shared memory backed.
For direct file-backed memory ING, set it to "/tmp/apc. XXXXXX" (exactly 6 X ).
To use the POSIX shm_open/mmap style, you must set it to "/apc. shm. XXXXXX.
You can also set it to "/dev/zero" to use the kernel "/dev/zero" interface for anonymous ing memory.
If this command is not defined, anonymous ING is mandatory.
Apc. num_files_hint = 1000
; SYS
The approximate number of different source files that may be contained or requested on the Web server (recommended value: 1024 ~ 4096 ).
If you are not sure, set it to 0. this setting is mainly used for websites with thousands of source files.
Apc. optimization = 0
; Optimization level (recommended value: 0 ).
The positive integer value indicates that the optimizer is enabled. the higher the value, the more radical optimization is used.
; A higher value may have a very limited speed increase, but it is still being tested.
Apc. report_autofilter = Off
; SYS
; Whether to record all scripts that are automatically not cached due to early/late binding.
Apc. shm_segments = 1
; SYS
; The number of shared memory blocks allocated to the compiler buffer (recommended value: 1 ).
If APC consumes shared memory and the apc. shm_size command is set to the maximum value 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, recommended value: 128 ~ 256 ).
Some systems (including most BSD variants) have very few default shared memory blocks.
Apc. slam_defense = 0
; SYS (opposed to using this command, we recommend using the apc. write_lock command)
On very busy servers, whether it is to start the service or modify files,
; May be caused by multiple processes attempting to cache a file at the same time.
This command is used to set the percentage of cached steps skipped by a process when processing files that are not cached.
For example, if it is set to 75, it indicates that no cache is performed for files that are not cached, reducing the chance of collision.
We recommend that you set it to 0 to disable this feature.
Apc. stat = On
; SYS
; Whether to enable the script update check.
Be very careful when changing the command value.
The default value On indicates that APC checks whether the script is updated every time it requests the script,
If updated, the compiled content is automatically re-compiled and cached. However, this has a negative impact on performance.
If it is set to Off, the check is not performed, which greatly improves the performance.
To make the updated content take effect, you must restart the Web server.
This command is also valid for include/require files. However, you must note that,
If you are using a relative path, APC must check each include/require operation to locate the file.
You can skip the check using the absolute path. Therefore, you are encouraged to use the absolute path for the include/require operation.
Apc. user_entries_hint = 100
; SYS
; Similar to the num_files_hint command, only for different users.
If you are not sure, set it to 0.
Apc. write_lock = On
; SYS
Whether to enable the write lock.
On very busy servers, whether it is to start the service or modify files,
; May be caused by multiple processes attempting to cache a file at the same time.
; Enable this command to avoid competition conditions.
Apc. rfc1867 = Off
; SYS
After this command is enabled, for each upload file that contains the APC_UPLOAD_PROGRESS field before the file field, APC will automatically create an upload _ User cache entry (that is, the APC_UPLOAD_PROGRESS field value ).
3. php functions
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's Shared Memory Allocation information
Apc_store-Cache a variable in the data store

4. note:
Apc shares memory with apache processes. Therefore, only apache processes can be executed to store values in apc. common php processes cannot access apc shared memory.


Chapter 3 encoding techniques for improving PHP performance

0. replace double quotation marks with single quotes to include strings. this will be faster. Because PHP will search for variables in strings enclosed by double quotes, but not in single quotes. Note: Only echo can do this, it is a "function" that can treat multiple strings as parameters (echo is a language structure, not a real function, so double quotation marks are added to the function ).
1. if the class method can be defined as static, it should be defined as static as much as possible, and its speed will be increased by nearly four times.
2. $ row ['id'] is 7 times faster than $ row [id.
3. echo is faster than print, and multiple echo parameters are used to replace string connections, such as echo $ str1, $ str2.
4. determine the maximum number of cycles before executing the for loop. do not calculate the maximum value for each loop. use foreach instead.
5. cancel unnecessary variables, especially large arrays, to release the memory.
6. avoid using _ get ,__ set ,__ autoload whenever possible.
7. require_once () is expensive.
8. try to use the absolute path when you include the file, because it avoids PHP's speed of searching for the file in include_path, and it takes less time to parse the operating system path.
9. if you want to know the TIME when the script starts to be executed (I .e. when the SERVER receives a client REQUEST), use $ _ SERVER ['request _ time'] instead of time ().
10. functions use the same functions instead of regular expressions.
11. the str_replace function is faster than the preg_replace function, but the strtr function is four times more efficient than the str_replace function.
12. if a string replacement function can take an array or character as a parameter and the parameter length is not too long, you can consider writing an additional replacement code so that each parameter passing is a character, instead of writing only one line of code to accept arrays as query and replacement parameters.
13. Using the select branch statement is better than using multiple if and else if statements.
14. blocking error messages with @ is very inefficient and extremely inefficient.
15. open the mod_deflate module of apache to speed up web page browsing.
16. when the database connection is used up, it should be switched off. do not use persistent connections.
17. the error message is expensive.
18. increase the local variable in the method at the fastest speed. It is almost the same as calling a local variable in a function.
19. increasing a global variable is twice slower than increasing a local variable.
20. incrementing an object property (for example, $ this-> prop ++) is three times slower than incrementing a local variable.
21. increasing an unspecified local variable is 9 to 10 times slower than increasing a predefined local variable.
22. defining only one local variable without calling it in the function also slows down (to the extent that it is equivalent to increasing a local variable ). PHP will probably check whether global variables exist.
23. method calling seems to have nothing to do with the number of methods defined in the class, because I have added 10 methods before and after the test method, but the performance has not changed.
24. the methods in the derived class run faster than the same methods defined in the base class.
25. calling an empty function with a parameter takes seven to eight times to increment local variables. Similar method calls take nearly 15 times to increment local variables.
26. Apache parses a PHP script two to ten times slower than parsing a static HTML page. Use static HTML pages and less scripts as much as possible.
27. unless the script can be cached, it will be re-compiled every time it is called. The introduction of a PHP Cache mechanism can generally improve the performance by 25% to 100%, so as to avoid compilation overhead.
28. use memcached as much as possible. Memcached is a high-performance memory object cache system that can accelerate dynamic Web applications and reduce database load. It is useful for the cache of OP code, so that the script does not have to re-compile each request.
29. when operating a string and checking whether its length meets certain requirements, you will use the strlen () function. This function is executed quite quickly because it does not perform any calculations and only returns the known string length stored in the zval structure (C's built-in data structure, used to store PHP variables. However, because strlen () is a function, it is more or less slow, because function calls take many steps, such as lowercase letters, PHP does not distinguish between case-insensitive function names.) and hash searches are executed along with the called function. In some cases, you can use the isset () technique to accelerate your code execution.
(For example)
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 () is used as a language structure, this means that function search and lowercase letters are not required for execution. That is to say, in fact, you do not spend too much money in the top-level code that checks the string length.
34. when the execution variable $ I increments or decreases, $ I ++ is slower than ++ $ I. This difference is exclusive to PHP and does not apply to other languages. therefore, do not modify your C or Java code and expect them to become faster and useless immediately. ++ $ I is faster because it only requires three commands (opcodes), and $ I ++ requires four commands. In fact, a temporary variable is generated in post-increment mode, which is then incremented. The pre-increment directly increases on the original value. This is a kind of optimization, as the Zend PHP optimizer does. Keeping this optimization processing in mind is a good idea, because not all command optimizers perform the same optimization and there are a large number of Internet service providers (ISPs) that do not have command optimizers) and server.
35. object-oriented (OOP) is not required. object-oriented usually has a high overhead, and each method and object call consumes a lot of memory.
36. arrays are also useful instead of using classes to implement all data structures.
37. do not subdivide the methods too much. think carefully about the code you actually intend to reuse?
38. when you need it, you can always break down the code into methods.
39. try to use a large number of PHP built-in functions.
40. if there are a large number of time-consuming functions in the code, you can consider using C extension to implement them.
41. profile your code. The validator will tell you how much time the code consumes. The Xdebug debugger contains an inspection program, which can display the code bottleneck in general.
42. mod_zip can be used as an Apache module to instantly compress your data and reduce the data transmission volume by 80%.
43. when file_get_contents can be used to replace file, fopen, feof, fgets, and other methods, try to use file_get_contents, because its efficiency is much higher! Note the PHP version of file_get_contents when opening a URL file;
44. perform as few file operations as possible, although PHP file operations are not efficient;
45. optimize Select SQL statements and perform Insert and Update operations as little as possible;
46. try to use PHP internal functions as much as possible (however, in order to find a function that does not exist in PHP, it is a waste of time to write a user-defined function. this is an empirical problem !);
47. do not use ** variables inside the loop, especially large variables: objects (isn't it just a matter of attention in PHP ?);
48. do not use nested values for multi-dimensional arrays;
49. do not use regular expressions when using internal PHP strings to operate functions;
50. foreach is more efficient. use foreach instead of the while and for loops;
51. use single quotes instead of double quotes to reference strings;
52. replace I = I + 1 with I + = 1. In line with the c/c ++ habits, high efficiency ";
53. for global variables, unset () should be used up;

Kernel (php. ini), performance optimization php. ini Chapter 1 optimization for too many system calls I this optimization for too many syscall calls problems, so use strace to track apac...

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.