I have been doing PHP programming for two years. Now I will summarize and share some of the more practical methods to improve PHP performance. Novices are welcome to watch and experts can correct me!
1. Use single quotes instead of double quotes to include strings, which will be faster. Because PHP will search for variables in strings surrounded by double quotes, single quotes will not. Note: only echo can do this, it is a "function" that can take multiple strings as parameters (Annotation: PHP Manual It is said that echo is a language structure, not a real function, so the function is enclosed in double quotes).
2. If you can define a class method as static, try to define it as static, and its speed will be increased by nearly 4 times.
3. The speed of $row['id'] is 7 times that of $row[id].
4. Echo is faster than print, and it is more efficient to use commas instead of periods instead of string connections when using echo output, such as echo $str1,$str2.
5. Determine the maximum number of loops before executing the for loop. Do not put count/strlen/sizeof and other things that must be repeated every time but have the same result into the conditional statement of the for loop. In addition, it is best to use foreach instead of for loop.
6. Log out unused variables in a timely manner, especially large arrays, objects, etc., in order to release memory.
7. require_once() is expensive. According to test data, using require_once is 3-4 times slower than require. The specific solution can be to first check whether the reference exists and then decide whether require is required.
8. Try not to use relative paths when including and require files, because when using relative paths, it will first look for the specified php include path, and then look for the current directory, so too many paths will be checked, so the best option is to use Absolute path.
9. If you want to know the time when the script starts executing (that is, the server receives the client request), it is better to use $_SERVER['REQUEST_TIME'] than time(). As for the role of $_SERVER['REQUEST_TIME'], the documentation explains that this variable stores the timestamp when the page request starts. Valid since PHP 5.1.0. The effect is the same as the time function.
10. Wherever functions can be used instead of regular expressions, try to use functions instead.
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. The strtr() function is used to convert specific characters in a string.
12. Do not make unnecessary substitutions. Even if there is no substitution operation, using str_replace will allocate memory for its parameters. Very slow! Solution: Use strpos to first search for relevant information to see if it needs to be replaced, and then replace it if necessary. The actual efficiency comparison is: If replacement is needed: The efficiency is almost equal, the difference is around 0.1%. If no replacement is needed: using strpos will increase the speed by 200%.
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 parameter passed is one character instead of just one line. The code accepts arrays as parameters for query and replace.
13. It is better to use a selective branch statement (ie switch case) than to use multiple if, else if statements.
14. Don’t abuse the @ operator. Although @ looks simple, there are actually a lot of operations behind the scenes. The efficiency difference between using @ and not using @ is: 3 times. Especially don't use @ inside a loop.
15. Opening the mod_deflate module of apache can improve the browsing speed of web pages. The mod_deflate module provides the DEFLATE output filter, which allows the server to compress the output content before sending it to the client to save bandwidth. Please refer to the relevant documentation for specific settings.
16. Increasing local variables in methods is the fastest. Almost as fast as calling local variables in a function. Incrementing a global variable is 2 times slower than incrementing a local variable.
17. Increasing an object property (eg: $this->num++) in a method is 3 times slower than incrementing a local variable (eg: $num).
18. Incrementing an undefined local variable is 9 to 10 times slower than incrementing a predefined local variable.
19. Just defining a local variable without calling it in a function will also slow down the speed (to the same extent as incrementing a local variable). PHP will probably check to see if a global variable exists.
20. Method calls appear to be independent of the number of methods defined in the class, as I added 10 methods (both before and after the test method) and there was no change in performance.
21. Methods in derived classes run faster than the same methods defined in base classes.
22. Calling an empty function with one parameter takes the same time as performing 7 to 8 local variable increment operations. A similar method call takes close to 15 local variable increment operations.
23. The time it takes for Apache to parse a PHP script is 2 to 10 times slower than parsing a static HTML page. Try to use more static HTML pages and less scripts.
24. Unless the script can be cached, it will be recompiled every time it is called. Introducing a PHP caching mechanism can usually improve performance by 25% to 100% to eliminate compilation overhead.
25. Try to cache as much as possible, you can use memcached. Memcached is a high-performance memory object caching system that can be used to accelerate dynamic web applications and reduce database load. Caching of OP codes is useful so that scripts do not have to be recompiled for each request.
26. When operating a string and need to check whether its length meets certain requirements, you will naturally use the strlen() function. This function executes quite quickly because it does not do any calculations and just returns the known string length stored in the zval structure (C's built-in data structure used to store PHP variables). However, since strlen() is a function, it will be somewhat slow, because the function call will go through many steps, such as lowercase letters (Annotation: refers to the lowercase function name, PHP does not distinguish between uppercase and lowercase function names), hash search, Will be executed together with the called function. In some cases, you can use the isset() trick to speed up the execution of your code, as in the following example:
if (strlen($str) < 6) { echo 'str不满6个字符'; }
(Compare with the tips below)
if (!isset($str{6})) { echo 'str不满6个字符'; }
Calling isset() is faster than strlen() because isset(), as a language construct, means that its execution does not require function lookup and letter lowercase. That is, you actually don't spend much overhead in the top-level code checking the string length.
27. When executing the increment or decrement of variable $i, $i++ will be slower than ++$i. This difference is specific to PHP and does not apply to other languages, so please don't modify your C or Java code and expect it to be instantly faster, it won't work. ++$i is faster because it only requires 3 instructions (opcodes), while $i++ requires 4 instructions. Post-increment actually creates a temporary variable that is subsequently incremented. Prefix increment increases directly on the original value. This is a form of optimization, as done by Zend's PHP optimizer. It's a good idea to keep this optimization in mind because not all command optimizers do the same optimizations, and there are a large number of ISPs and servers that don't have command optimizers installed.
28. Not everything must be object-oriented (OOP). Object-oriented is often very expensive, and each method and object call consumes a lot of memory.
29. It is not necessary to use classes to implement all data structures. Arrays are also very useful.
30. Don’t subdivide methods too much. Think carefully about which code you really intend to reuse.
31. Try to use PHP built-in functions where possible.
32. If there are a large number of time-consuming functions in the code, you can consider implementing them using C extensions.
33. Profile your code. The checker will tell you which parts of the code take how much time. The Xdebug debugger includes inspection routines that evaluate the overall integrity of your code and reveal bottlenecks in your code.
34. mod_zip can be used as an Apache module to instantly compress your data and reduce data transmission volume by 80%.
35. When file_get_contents can be used instead of file, fopen, feof, fgets and other series of methods, try to use file_get_contents because it is much more efficient! But pay attention to the PHP version problem of file_get_contents when opening a URL file. ;
36. Conduct file operations as little as possible, although PHP’s file operations are not low in efficiency.
37. Optimize the Select SQL statement. Try to use uppercase instead of lowercase for SQL keywords except for table fields.
38. Do not declare variables inside the loop, especially large variables: objects. The solution is to predefine the variables that need to be declared before the loop.
39. Try not to loop and nest assignments in multi-dimensional arrays.
40. Do not use regular expressions when you can use PHP’s internal string manipulation functions.
41. foreach is more efficient than while and for.
42. Use i+=1 instead of i=i+1. It conforms to the habits of c/c++ and is highly efficient;
43. Global variables should be unset()ed when used;
44. Intentionally ignore the php closing tag (i.e.?>).
45. Before writing or saving files, please ensure that the directory is writable. If it is not writable, an error message will be output. This will save you a lot of debugging time. Especially in Linux systems, permissions need to be dealt with. Improper directory permissions can cause many, many problems, and files may not be readable, etc. For example, the following example:
$contents = "All the content"; $file_path = "/var/www/project/content.txt"; file_put_contents($file_path ,$contents);
This is generally true, but there are some indirect issues, file_put_contents may fail for several reasons:
(1) The parent directory does not exist
(2) The directory exists, but is not writable
(3) The file is write-locked?
Therefore, it is better to do a clear check before writing the file. The correct way to write it is as follows:
<?php $contents='测试内容'; $dir='/var/www/project'; $file_path=$dir."/content.txt"; if(is_writable($dir)){ file_put_contents($file_path,$contents); }else{ die('目录不存在或者目录不可写!'); }
46. Do not rely on the submit button value to check the form submission behavior, such as the following situation:
if($_POST['submit'] == 'Save') { //Save the things }
Most of the above is true, except that the app is multi-lingual. 'Save' may mean other things, how do you distinguish between them, so don't rely on the value of the submit button. The correct way to write it is as follows:
if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ) { //Save the things }
47. Do not use the $_SESSION variable directly
A simple example:
$_SESSION['username'] = $username; or $username = $_SESSION['username'];
这会导致某些问题,如果在同个域名中运行了多个应用,session 变量可能会冲突,两个不同的应用可能使用同一个session key,例如,一个前端门户,和一个后台管理系统使用同一域名。对于这种情况,解决方案如下,使用应用相关的key和一个包装函数:
<?php define('APP_ID','abc_corp_ecommerce'); function session_get($key){ $k=APP_ID.'.'.$key; if(isset($_SESSION[$k])){ return $_SESSION[$k]; } return false; } function session_set($key,$value){ $k=APP_ID.'.'.$key; $_SESSION[$k]=$value; return true; }
48、将你的工具函数封装到类中,假如你在某文件中定义了很多工具函数,如下:
<?php function utility_a(){ //This function does a utility thing like string processing } function utility_b(){ //This function does nother utility thing like database processing } function utility_c(){ //This function is .. }
但这些函数的使用分散到应用各处,那么你可以将他们封装到某个类中:
<?php class Utility { public static function utility_a(){} public static function utility_b(){} public static function utility_c(){} }
调用方法如:$a=Utility::utility_a(); 或者 $b=Utility::utility_b();
这样做的好处是,如果php内建有同名的函数,这样就可以避免冲突,维护起来也相当容易。
49、使用array_map快速处理数组,比如说你想 trim 数组中的所有元素,新手可能会:
foreach($arr as $c => $v) { $arr[$c] = trim($v); }
但和上面的比起来使用 array_map 更简单,比如:
$arr = array_map('trim',$arr);
这会为$arr数组的每个元素都申请调用trim函数,另一个类似的函数是 array_walk,具体用法请查阅文档学习更多技巧.
50、使用 php filter 验证数据,你肯定曾使用过正则表达式验证 email ,ip地址等,可以尝试使用 php内置的 filter 扩展来完成相关验证和检查输入。
51、确保你的脚本由始至终都使用单一的数据库连接,在开始处正确的打开连接,使用它直到结束,最后关闭它,像下面这种在函数中打开连接是非常糟糕的:
<?php function add_to_cart() { $db = new Database(); $db->query("INSERT INTO cart ....."); } function empty_cart() { $db = new Database(); $db->query("DELETE FROM cart ....."); }
以上事例因为创建连接需要时间和占用内存,所以会拖慢应用的速度。数据库的链接最好使用单例模式。