<<
PHP Optimization – tuning PHP primarily involves adjusting and configuring key parameters in php.ini. Below, let’s look at how to set some parameters in php.ini that have a significant impact on performance.
# vi /etc/php.ini
(1) Disabling PHP Functions – Find:
disable_functions =
This option specifies which PHP functions are disabled. Some PHP functions pose considerable security risks, as they can directly execute system-level script commands. If these functions are allowed and a vulnerability exists in the PHP program, the damage can be severe! Below is our recommended list of functions to disable:
disable_functions = phpinfo,passthru,exec,system,popen,chroot,escapeshellcmd,escapeshellarg,shell_exec,proc_open,proc_get_status
Note: If your server hosts PHP programs that monitor system status, do not disable functions such as shell_exec, proc_open, proc_get_status.
(2) PHP Script Execution Time – Find:
max_execution_time = 30
This option sets the maximum execution time for a PHP program. If a PHP script is requested and fails to complete execution within max_execution_time, PHP will stop executing and return a timeout error to the client. Unless you have special requirements, you can leave this at the default of 30 seconds. If your PHP scripts genuinely need a longer execution time, you can increase this value accordingly.
(3) PHP Script Memory Limit – Find:
memory_limit = 8M
This option specifies the maximum memory a PHP script can consume during processing, defaulting to 8MB. If your server has 1GB of RAM or more, consider setting this to 12MB for faster PHP script processing efficiency.
(4) PHP Global Function Declaration – Find:
register_globals = Off
Many PHP configuration articles online recommend setting this option to On. In reality, this is an extremely dangerous setting that can lead to serious security issues. Unless you have a very specific need, we strongly recommend keeping the default setting!
(5) PHP Upload File Size Limit – Find:
upload_max_filesize = 2M
This option sets the maximum allowed upload file size for PHP, defaulting to 2MB. You can increase this value according to your actual application needs.
(6) Session Storage Medium – Find:
session.save_path
If your PHP application uses Sessions, you can set the Session storage location to /dev/shm. /dev/shm is a TMPFS file system unique to Linux, using memory as its primary storage medium. It is superior to a RAMDISK because it can use DISKSWAP as a supplement, is a built-in system feature module, and requires no extra configuration. Just think, how much faster is switching from disk I/O operations to memory operations? Just note that data stored in /dev/shm will be lost upon server restart. However, for Session data, this is usually insignificant.
Due to my limited knowledge, I’m still not entirely sure why some of these work. If you have better suggestions, feel free to contribute anytime!
0. Use single quotes instead of double quotes for strings. It’s faster because PHP searches for variables inside double-quoted strings but not single-quoted ones. Note: this applies specifically to echo, which is a “function” that can take multiple strings as parameters (Translator’s note: the PHP manual states echo is a language construct, not a true function, hence the quotation marks).
PS: In single quotes, PHP doesn’t automatically search for variables or escape characters, making it significantly more efficient. Since strings generally don’t contain variables, using double quotes leads to poorer performance.
1. If you can define class methods as static, do so. The speed will improve by nearly 4 times.
PS: In practice, the speed difference between functions, methods, and static methods isn’t huge. See the article “PHP Function Implementation Principles and Performance Analysis [Reprint]” for details.
2. $row[‘id’] is 7 times faster than $row[id].
PS: I don’t fully understand, but the difference seems to be that the latter first checks if ‘id’ is a defined constant, and if not, automatically converts it to a string.
3. echo is faster than print, and use echo’s multiple parameters (referring to comma-separated, not concatenated with a dot), e.g., echo $str1,$str2.
PS: Using echo $str1.$str2 requires the PHP engine to first concatenate all variables, then output them. With echo $str1,$str2, the PHP engine outputs them sequentially.
4. Determine the maximum loop count before executing a for loop. Don’t recalculate the maximum value in each iteration. It’s best to use foreach instead.
PS: Operations like count() and strlen() are actually O(1), so they don’t add much overhead. Still, avoiding per-iteration calculation is a good strategy. Best to use foreach instead of for for greater efficiency. If you’re concerned about the copy cost of foreach($array as $var), use references like foreach($array as &$var).
5. Unset unused variables, especially large arrays, to free memory.
PS: If I recall correctly, unset($array) doesn’t immediately release memory, but freeing memory as soon as possible is a good habit.
6. Try to avoid using __get, __set, __autoload.
7. require_once() is expensive.
PS: require_once and include_once need to check for duplication, making them less efficient. However, this efficiency issue has been largely resolved since PHP 5.2.
8. When including files, try to use absolute paths. This avoids PHP searching through include_path and reduces the time needed to resolve the operating system path.
PS: Agreed. Also, try to minimize using ini_set() to change include_path.
9. If you want to know when a script started executing (i.e., when the server received the client request), use $_SERVER[‘REQUEST_TIME’] instead of time().
PS: $_SERVER[‘REQUEST_TIME’] stores the timestamp of when the request was initiated, while time() returns the current Unix timestamp.
10. Use functions instead of regular expressions to accomplish the same task.
PS: Such functions include strtok, strstr, strpos, str_replace, substr, explode, implode, etc.
11. The str_replace function is faster than preg_replace, but strtr is four times faster than str_replace.
PS: String operations are faster than regular expression replacements.
12. If a string replacement function accepts arrays or characters as parameters and the parameter length isn’t too long, consider writing a separate replacement routine that passes a character each time, instead of a single line of code accepting arrays for search and replace parameters.
PS: You need to consider the overhead difference between built-in functions and user-defined functions. This approach might not be worth the effort.
13. Using switch case statements is better than using multiple if, else if statements.
PS: PHP’s switch supports both numeric and string variables, making it more versatile than C’s switch. It’s recommended to use it.
14. Using @ to suppress error messages is very inefficient, extremely inefficient.
PS: Is there an alternative? If not, you might still have to use it…
15. Enable Apache’s mod_deflate module to improve webpage browsing speed.
16. Close database connections when done. Don’t use persistent connections.
PS: Before connecting, it’s best to set appropriate timeout mechanisms, such as connection timeout, read/write timeout, and wait timeout.
17. Error messages are expensive.
18. Incrementing a local variable within a method is fastest. Its speed is nearly equivalent to calling a local variable within a function.
19. Incrementing a global variable is 2 times slower than incrementing a local variable.
20. Incrementing an object property (e.g., $this->prop++) is 3 times slower than incrementing a local variable.
21. Incrementing an undeclared local variable is 9 to 10 times slower than incrementing a pre-defined one.
22. Just defining a local variable without using it in a function also slows things down (comparable to incrementing a local variable). PHP likely checks to see if a global variable exists.
23. Method calls seem independent of the number of methods defined in a class, as I added 10 methods (both before and after testing the method) and saw no performance change.
24. Methods in derived classes run faster than the same methods defined in a base class.
25. Calling an empty function with one parameter takes time equivalent to 7 or 8 local variable increment operations. A similar method call takes time approaching 15 local variable increment operations.
26. Apache parses a PHP script 2 to 10 times slower than a static HTML page. Use static HTML pages as much as possible, and scripts less frequently.
27. Unless a script can be cached, it’s recompiled on every call. Introducing a PHP caching mechanism can typically boost performance by 25% to 100% by eliminating compilation overhead.
28. Cache wherever possible, using tools like memcached. Memcached is a high-performance, distributed memory object caching system used to accelerate dynamic web applications and reduce database load. Caching opcodes is very useful, preventing scripts from needing to be recompiled for every request.
29. When operating on a string and needing to check its length against a requirement, you’d naturally think of using strlen(). This function executes quite fast as it doesn’t perform any calculation; it simply returns the known string length stored in the zval structure (C’s built-in data structure for storing PHP variables). However, since strlen() is a function, it incurs some overhead because a function call involves many steps, like name lowercasing and hash lookups, which execute along with the called function. In some cases, you can use the isset() trick to speed up code execution.
(Example below)
if (strlen($foo) < 5) { echo “Foo is too short”$$ }
(Compare with the following trick)
if (!isset($foo{5})) { echo “Foo is too short”$$ }
Calling isset() happens to be faster than strlen() because, unlike the latter, isset() is a language construct, meaning its execution doesn’t require a function lookup or name lowercasing. In other words, you incur very little overhead in the top-level code for checking string length.
PS: Learned something new.
30. When incrementing or decrementing a variable $i, $i++ is slightly slower than ++$i. This difference is specific to PHP and doesn’t apply to other languages, so please don’t modify your C or Java code expecting them to immediately become faster—it won’t work. ++$i is faster because it requires only 3 instructions (opcodes), whereas $i++ needs 4. Post-increment actually creates a temporary variable, which is then incremented. Pre-increment directly increments the original value. This is a type of optimization, much like what Zend’s PHP optimizer does. Keeping this optimization in mind is a good idea, as not all opcode optimizers perform this optimization, and there are many ISPs and servers without an opcode optimizer installed.
31. Don’t feel compelled to make everything Object-Oriented (OOP). OOP often involves significant overhead; every method and object call consumes considerable memory.
32. You don’t have to use classes for all data structures; arrays are very useful too.
33. Don’t break methods down excessively. Think carefully about which code you actually intend to reuse?
34. You can always decompose code into methods when you need to.
PS: Decompose into methods appropriately. For small, high-frequency methods, consider writing the code directly to reduce function stack overhead. Also, avoid deep method nesting, as it significantly impacts PHP’s execution efficiency.
35. Utilize PHP’s vast array of built-in functions as much as possible.
36. If your code contains many time-consuming functions, consider implementing them as C extensions.
37. Profile your code. A profiler tells you which parts of the code consume how much time. The Xdebug debugger includes a profiler. Profiling generally reveals the bottlenecks in your code.
38. mod_zip can be used as an Apache module to compress your data on the fly, reducing data transfer volume by up to 80%.
39. When you can use file_get_contents to replace a series of functions like file, fopen, feof,