PHP performance optimization (php. ini), performance optimization php. ini

Source: Internet
Author: User
Tags apc apache log smarty template

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

Copy codeThe 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;

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.