Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Collection of methods for PHP performance Optimization

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly explains the "PHP performance optimization method collection", the content of the article is simple and clear, easy to learn and understand, now please follow the editor's train of thought slowly in depth, together to study and learn "PHP performance optimization method collection"!

The first chapter is the optimization of too many system calls.

My optimization this time aims at the problem of too many syscall calls, so I use the strace trace apache for analysis.

1. Apache2ctl-X &

Start the httpd process with the-X (debug) parameter, and only one httpd process is started at this time

2. Ps-ef | grep httpd

Find the pid that needs strace

3. Strace-p $PID-o / tmp/strace.log

Send a http request to httpd and you will see the strace message.

I. include_path problem

You can generally see a lot of this kind of information:

Stat64 ("/ error/dir/test.php", 0xbfab4b9c) =-1 ENOENT (No such file or directory)

Solution:

1. Set include_path in the application php and remove'.' And other relative paths, put the directory that contains more files to the front. Make sure that you can find it quickly when traversing include_path.

two。 Using absolute paths for include,require,include_once,require_once

3. Using the automatic loading mechanism of php

II. Rewrite configuration of apache

The copy 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 rewrite here is poorly configured because it has an extra syscall for each request.

Stat64 ("/ index.php", 0xbfab4b9c) =-1 ENOENT (No such file or directory)

III. Apache log problem

When we were testing a problem, we found that if information such as access time was recorded in the custom log, there would be a lot more.

Stat64 ("/ etc/localtime", {st_mode=S_IFREG | 0644, st_size=165,...}) = 0

If you record a large number of logs, the performance degradation is very serious, for simple applications, recording complex logs, the performance will be reduced by 30 times.

Solution:

A http layer of proxy, such as haproxy,nginx, is mounted on a plurality of apache front ends. Keep a log in these places. The load on the access layer is generally not high, so proxy can do some logging work. In this configuration, the log for apache can be turned off.

IV. Realpath () problem

You can take a look at this article: http://bugs.php.net/bug.php?id=43864

After too many lstat64 calls, both the host CPU and IO are relatively high.

The reason is that because php5.2.x 's implementation of realpath () is not good enough, lstat64 () will be called step by step for the directory level.

To solve this problem, it uses realpath_cache to store the realpath for a file. Here, only the realpath of the leaf node is stored, but there is no storage for the content on the path, so the lstat64 is called step by step when doing the "/ a/b/c/d/e/f/g/a.php" realpath check, and when the "/ a/b/c/d/e/f/g/ b.php" check is done, the "/ a/b/c/d/e/f/g/" is also checked step by step. So some optimization suggestions are to "reduce the directory level, or even put it in the root directory". Of course, I don't recommend it. Since 5.3.0, php has implemented realpath () efficiently, and the middle path of the path realpath has also been cached. In the above case, when checking "/ a/b/c/d/e/f/g/b.php", it will only do a "b.php" check. Therefore, upgrading to a version above php5.3.0 can solve this problem very well.

Solution:

1. Use include_once and require_once as little as possible

Because these two functions do a realpath check to prevent symbolic links from causing repeated loading. You can reduce the number of realpath calls without them.

two。 Reasonable setting of realpath_cache_size and realpath_cache_ttl parameters in php.ini

Now that realpath_cache is used, there must be a size limit. For projects that use a lot of files, such as Zend Framework, the default realpath_cache_size=16k may be too small. You need to increase this setting. It is recommended to set it above 256K. In addition, the default realpath_cache_ttl=120,2 minute is out of date, so it should be set to 3600 (1 hour) anyway.

It should be noted here that this realpath_cache is exclusive to every apache process, so it eats a lot of memory and cannot be set too large.

3. Upgrade to php5.3.x

There is nothing to say, if there is no problem with the application after detailed testing, then it is recommended to upgrade to a higher version.

5. The use of APC

Apc can cache the opcode code of php, which generally improves the performance by 30%. But the default apc.stat=1, so that each request will access the need to use the php file to see if the file has been updated, has decided whether to recompile the php file. This is very performance-consuming, so it is recommended to turn it off.

Solution:

1. Set apc.stat=0 so that you don't have to access the php file you need every time you request it.

It is important to note that every time the release changes the php file, you must call apc_clear () to clear the apc cache, otherwise your code will never take effect.

VI. Smarty tuning

For sites with better modularization and more applications, if you use the smarty template system, you need to tune smarty at this time, otherwise the cost of the smarty part will be considerable. According to one experience, smarty can account for about 10% of the cost.

By default, smarty detects whether each template file is updated and decides whether to recompile the template file. If there are more template files, there will be a lot of stat system calls, plus context switch, it will be expensive.

Solution:

1. $smarty- > compile_check = false

Remove each test, but after that, delete the compiled template of the compile_dir directory every time you send it, or your template file will never take effect.

two。 If possible, you can use the cache feature.

Conclusion

After the above tuning, the conclusions are as follows:

1. Upgrade to php5.3.1 to enable the above optimization, which is more than 10% higher than 5.2.3

two。 Under the optimized configuration, a search application developed with Zend Framework can achieve 210/rps requests per second.

3. Under the optimized configuration, a search application developed with doophp framework can achieve 450/rps requests per second.

Chapter 2 using APC caching

The execution flow of php program

-"client (browser) request Get hello.php

"the cgi server receives a request (such as apache) and looks for a handler for php (such as mod_php) according to the configuration.

-- "apache loads the handler of php, and the handler of php reads the interpretation environment in which php.ini initializes php."

-- "mod_php locates the hell.php and loads it into memory

-- "mod_php compiles source code into an opcode tree

-- "mod_php executes opcode tree

-- "generate the results to the browser

In this process, there are a few points to pay attention to:

1. Speak to many code files, especially containing a lot of include or require files. They take more time and parsing and generate intermediate code.

2. Even if the PHP code file has not changed, the execution process will be carried out strictly according to the process. That is, regardless of whether your program has changed or not, you need to recompile and generate opcode each time you call it. (in fact, this is the reason why the compilation cache exists.)

3. This process occurs not only in the main code files, but also in every include and require. (this can continue to be optimized)

Which places can be optimized?

1. Make mod_php fast- CGI, avoid having to load this module every time, and initialize the interpretation environment of php every time.

2. Cache the opcode of the php file to avoid compiling it every time.

APC can be used to implement point 2. The compilation cache removes the parsing process from performing PHP, so it is very effective for applications that contain a lot of PHP code. Under normal circumstances, the speed can be increased 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 compiled cache. For example, there are now two files: main.php and tobeInclude.php, with the statement include tobeInclude.php' in main.php. Assume that the suffix of the intermediate code is .op (which is not really the case). Then main.php= > main.op, tobeInclude.php= > tobeInclude.op after adding cache cache. But when PHP executes main.php, she still needs to parse the include command in main.op and call the contents of tobeInclude.op. The specific process is like this.

... = > execute main.op= > execute tobeInclude.op= >...

Instead of simply performing main.op in between

So "too many include files will degrade the performance of the program."

The specific configuration of APC.

Alternative PHP Cache (APC) is a free and public cache of optimized code for PHP. It is used to provide a free, open and robust architecture to cache and optimize the intermediate code of PHP.

The official website of APC is 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 directory where php references modules, and modify permission 755

2. Configuration

Apc.enabled boolean

Apc.optimization optimization

Options can be changed in the script

Detailed explanation of APC PHP.ini configuration options

[APC]

Alternative PHP Cache is used to cache and optimize PHP intermediate code

Apc.cache_by_default = On

; SYS

Whether buffering is enabled for all files by default.

If set to Off and used with an apc.filters instruction that begins 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, this directive is opened 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, write a temporary file first, and then mv the file to its final name.

Text editors and programs such as cp and tar do not operate this way, resulting in the possibility of buffering incomplete files.

The default value of 2 means that if it is found that the modification time is less than 2 seconds from the access time when accessing the file, it will not be buffered.

The unfortunate visitor may get incomplete content, but the bad effect will not be magnified by caching.

If you can make sure that all update operations are atomic, you can turn off 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 comma-separated list of POSIX extended regular expressions

If the source file name matches any pattern, the file is not cached

Note that the file name used to match is the file name passed to include/require, not the absolute path.

If the first character of a regular expression is "+", it means that any file that matches the expression will be cached

If the first character is "-", no matches will be cached. "-" is the default value and can be omitted.

Apc.ttl = 0

; SYS

The number of seconds that cache entries are allowed to stay in the buffer 0 means never time 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, except for each user, 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.gc_ttl = 3600

; SYS

The number of seconds that cached entries can exist in the garbage collection table

This value provides a security measure, even if a server process crashes while executing the cached source file

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.

Set to zero to disable this feature.

Apc.include_once_override = Off

; SYS

Please leave it as Off, otherwise it may lead to unexpected results.

Apc.max_file_size = 1m

; SYS

Prevent files larger than this size from being 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-style file mask passed to the mmap module (the recommended value is "/ tmp/apc.XXXXXX").

This mask is used to determine whether the memory-mapped area is to be file-backed or shared memory backed.

For direct file-backed memory mapping, set to "/ tmp/apc.XXXXXX" (exactly 6 Xs).

To use POSIX-style shm_open/mmap, you need to set it to "/ apc.shm.XXXXXX".

You can also set it to "/ dev/zero" to use the kernel's "/ dev/zero" interface for anonymous mapped memory.

Not defining this directive means that anonymous mapping is enforced

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 102404096).

If you are not sure, set it to 0; this setting is mainly used for sites with thousands of source files.

Apc.optimization = 0

Optimization level (recommended value is 0).

A positive integer value means that the optimizer is enabled, and the higher the value, the more aggressive optimization is used.

Higher values may have a very limited speed increase, but they are 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 for the compiler buffer (the recommended value is 1).

If the APC runs out of shared memory and the apc.shm_size instruction 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) default to very small blocks of shared memory.

Apc.slam_defense = 0

; SYS (opposed to the use of this directive, it is recommended to use the apc.write_lock directive)

On a very busy server, whether starting the service or modifying the file

Can result in race conditions due to attempts by multiple processes to cache a file at the same time.

This directive sets the percentage that the process skips the caching step when processing files that are not cached

For example, setting it to 75 means there is a 75% chance that files that are not cached will not be cached, thus reducing the chance of collisions.

; encourage to disable this feature by setting it to 0.

Apc.stat = On

; SYS

; whether script update checking is enabled.

Be very careful to change the value of this instruction.

The default value of On means that APC checks whether the script has been updated every time it is requested

Automatically recompiles and caches the compiled content if updated. However, this has a negative impact on performance.

If set to Off, there is no check, resulting in a significant performance improvement.

But in order for the update to take effect, you must restart the Web server.

This directive is also valid for include/require files. But it's important to note that

If you are using a relative path, APC must check every include/require to locate the file.

Use absolute paths to skip checking, so you are encouraged to use absolute paths for include/require operations.

Apc.user_entries_hint = 100

; SYS

Similar to the num_files_hint directive, but for each different user.

If you are not sure, set it to 0.

Apc.write_lock = On

; SYS

Whether write locks are enabled.

On a very busy server, whether starting the service or modifying the file

Can result in race conditions due to attempts by multiple processes to cache a file at the same time.

Enable this directive to avoid the emergence of competitive conditions

Apc.rfc1867 = Off

; SYS

When the directive is opened, APC will automatically create a user cache entry for upload_ (that is, the value of the file field) for every uploaded file that contains an APC_UPLOAD_PROGRESS field just before the APC_UPLOAD_PROGRESS 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's Shared Memory Allocation information

Apc_store-Cache a variable in the data store

4. Note:

Apc shares memory with apache processes, so it is only possible to store values in apc when executing apache processes. Ordinary php processes cannot access apc shared memory.

Chapter 3 coding techniques to improve the performance of PHP

Use single quotation marks instead of double quotation marks to include strings, which is faster. Because PHP will search for variables in strings surrounded by double quotes, while single quotes will not, note: only echo can do this, it is a "function" that can take multiple strings as parameters. (translation note: PHP manual says that echo is a language structure, not a real function, so put the function in double quotes).

1. If you can define the method of a class as static, try to define it as static, which will be nearly 4 times faster.

2. The speed of $row ['id'] is seven times that of $row [id].

3. Echo is faster than print and uses multiple parameters of echo instead of string concatenation, such as echo $str1,$str2.

4. Determine the maximum number of cycles before executing the for loop. Do not calculate the maximum value every time. It is best to use foreach instead.

5. Log out unused variables, especially large arrays, in order to free memory.

6. Avoid using _ _ get,__set,__autoload as much as possible.

7. Require_once () is expensive.

8. Include files use absolute paths as far as possible, because it avoids the speed at which PHP looks for files in include_path, and it takes less time to parse the operating system path.

9. If you want to know when the script starts to execute, using $_ SERVER ['REQUEST_TIME'] is better than time ().

10. The function performs the same function instead of the regular expression.

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 accepts arrays or characters as parameters, and the parameter length is not too long, you can consider writing an additional replacement code so that each passing parameter is one character. Instead of just writing one line of code, you can accept an array as a query and replacement parameter.

13. It is better to use a selective branch statement (switch case) than to use multiple if,else if statements.

14. The practice of blocking error messages with @ is very inefficient, extremely inefficient.

15. Open the mod_deflate module of apache to improve the browsing speed of the web page.

16. The database connection should be turned off when it is finished, and do not use a long connection.

17. Error messages are expensive.

18. It is the fastest to increment local variables in the method. It is almost as fast as calling a local variable in a function.

19. Incrementing a global variable is twice as slow as increasing a local variable.

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

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

22. Defining a local variable without calling it in the function also slows down (to the extent equivalent to incrementing a local variable). PHP will probably check to see if there are global variables.

23. Method calls seem to have nothing to do with the number of methods defined in the class, because I added 10 methods (both before and after testing the methods), but there was no change in performance.

24. Methods in derived classes run faster than the same methods defined in the base class.

25. Calling an empty function with one parameter takes the same time as performing 7 to 8 local variable increment operations. The time taken by a similar method call is close to 15 local variable increment operations.

26. Apache parses a PHP script 2 to 10 times slower than parsing a static HTML page. Try to use more static HTML pages and fewer scripts.

27. Unless the script can be cached, it will be recompiled each time it is called. The introduction of a PHP caching mechanism can typically improve performance by 25 to 100 percent, eliminating compilation overhead.

28. Cache as much as possible, you can use memcached. Memcached is a high-performance in-memory object caching system that can be used to accelerate dynamic Web applications and reduce database load. Caching of OP code is useful so that scripts do not have to be recompiled for each request.

29. When you manipulate a string and need to verify that its length meets a certain requirement, you will naturally use the strlen () function. This function is fairly fast because it doesn't do any calculations and only returns the known string length stored in the zval structure (C's built-in data structure for storing PHP variables). However, because strlen () is a function, it is more or less slow, because function calls go through many steps, such as lowercase letters, hash lookups, and hash lookups that follow the called function. In some cases, you can use the isset () technique to accelerate the execution of your code.

(examples are as follows)

If (strlen ($foo) < 5) {echo "Foo is too short" $$}

(compare with the following techniques)

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 construct, means that its execution does not require function lookups and lowercase letters. That is, you don't actually spend much money on top-level code that checks the length of a string.

34. When executing the increment or decrement of the variable $I, $I will be slower than + + $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 be faster immediately. + + $I is faster because it requires only three instructions (opcodes), while $iTunes + requires four instructions. The post increment actually produces a temporary variable, which is then incremented. The pre-increment increases directly on the original value. This is one of the most optimized processes, as Zend's PHP optimizer does. It's a good idea to keep this optimization in mind, because not all instruction optimizers do the same, and there are a large number of Internet service providers (ISPs) and servers that do not have instruction optimizers.

35. You don't have to be object-oriented (OOP). Object-oriented is often very expensive, and each method and object call consumes a lot of memory.

36. Not all data structures are implemented with classes, and arrays are also useful.

37. Don't break down the methods too much. Think about what code you really intend to reuse.

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 your code, you can consider implementing them in a C extension.

41. Profile your code. The verifier will tell you which parts of the code take how much time. The Xdebug debugger includes a verification program, and the evaluation verification can show the bottleneck of the code in general.

42. Mod_zip can be used as an Apache module to compress your data in real time and reduce the amount of data transmission by 80%.

43. When file_get_contents can be used instead of file, fopen, feof, fgets and other methods, try to use file_get_contents, because it is much more efficient! But pay attention to the PHP version of file_get_contents when opening a URL file.

44. Do as few file operations as possible, although the file operation efficiency of PHP is not low.

45. Optimize Select SQL statements and perform as few Insert and Update operations as possible

46. Use PHP internal functions as much as possible (but I wasted the time I could have written a custom function in order to find a function that does not exist in PHP. )

47. No * * variables inside the loop, especially large variables: objects (it seems that this is not just a problem to pay attention to in PHP, is it?)

48. Try not to have cyclic nesting assignments for multidimensional arrays.

49. Do not use regular expressions when you can manipulate functions with PHP internal strings

50. Foreach is more efficient, using foreach instead of while and for cycles as far as possible

51. Replace double quotation marks with single quotation marks to quote strings

52. "replace i=i+1 with iTunes 1. It is in line with the habit of cUniverse plus, and it is still efficient."

53. For the global variable, unset () should be dropped when it is used up.

Thank you for your reading, the above is the content of "PHP performance optimization method collection". After the study of this article, I believe you have a deeper understanding of the problem of PHP performance optimization method collection, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report