Home  >  Article  >  Backend Development  >  Introduction to efficiency improvement and optimization methods in PHP

Introduction to efficiency improvement and optimization methods in PHP

黄舟
黄舟Original
2017-07-27 10:06:241534browse

In view of the experience and lessons learned from previous mini projects, many places are not standardized and efficient enough. Therefore, when further learning PHP, I made a certain summary of PHP-related knowledge based on Internet resources to prevent further detours.

PHP is the abbreviation of the English hypertext preprocessing language Hypertext Preprocessor. PHP is an HTML embedded language. It is a scripting language that is embedded in HTML documents and is executed on the server side. The language style is similar to C language and is widely used.

PHP's unique syntax mixes C, Java, perl and PHP's own syntax. It can execute dynamic web pages faster than CGI or perl. Compared with other programming languages, dynamic pages made with PHP embed programs into HTML documents for execution, and the execution efficiency is much higher than CGI that completely generates HTML tags; PHP can also execute compiled code, and the compilation can Achieve encryption and optimize code running, making the code run faster.

Some summary about PHP programming:

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

1. If you can define a class method as static, try to define it as static, and its speed will increase by nearly 4 times.

2. The speed of $row[’id’] is 7 times that of $row[id].

3. Echo is faster than print, and uses multiple parameters of echo (annotation: refers to using commas instead of periods) instead of string concatenation, such as echo $str1, $str2.

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

5. Unregister unused variables, especially large arrays, to free up memory.

6. Try to avoid using __get, __set, __autoload.

7. require_once() is expensive.

8. Try to use absolute paths when including files, because it avoids the speed of PHP searching for files in include_path, and the time required to parse the operating system path will be less.

9. If you want to know the time when the script starts executing (annotation: that is, the server receives the client request), it is better to use $_SERVER[‘REQUEST_TIME’] than time().

10. Functions replace regular expressions to complete the same function.

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 parameter passed is a character instead of Just write one line of code to accept arrays as parameters for query and replace.

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

14. Using @ to block error messages is very inefficient, extremely inefficient.

15. Turn on the mod_deflate module of apache to improve the browsing speed of web pages.

16. The database connection should be closed when finished using it. Do not use long connections.

17. Error messages are expensive.

18. Increasing local variables in the method is the fastest. Almost as fast as calling local variables in a function.

19. Incrementing a global variable is 2 times slower than incrementing 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. 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.

23. Method calls appear 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 method), but there was no change in performance.

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

25. 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 increments.

26. 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.

27. 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.

28. 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.

29. 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.

(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 lookup and letter lowercase. That is, you don't actually spend much overhead in the top-level code checking the string length.

30. The constant parameters of the file locking function flock——.

Shared lock (read operation)——LOCK_SH

Exclusive lock (write operation)——LOCK_EX

Release lock (whether shared or exclusive) - LOCK_UN

Anti-blocking - LOCK_NB

The lock operation can be released through the fclose() function.

31. Verify whether the string is a legal IP:

Do not use regular expressions, just use ip2long(). If it is legal, it will return a number, if it is not legal, it will return false.

32. Starting from PHP 5.3, you can use __DIR__ to get the directory where the current script is located, without the need for realpath (__FILE__).

33. Use checkdnsrr() to confirm the validity of some email addresses through the existence of domain names

This built-in function can ensure that each domain name corresponds to an IP address;

34. 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 perform the same optimizations, and there are a large number of Internet Service Providers (ISPs) and servers that do not have command optimizers equipped.

35. Not everything must be object-oriented (OOP). Object-oriented is often very expensive, and each method and object call consumes a lot of memory.

36. It is not necessary to use classes to implement all data structures. Arrays are also very useful.

37. Don’t subdivide the methods too much. Think carefully about which codes you really intend to reuse?

38. When you need it, you can always break the code into methods.

Decompose into methods appropriately. For methods with fewer lines and high frequency, try to write code directly, which can reduce function stack overhead; and method nesting should not be too deep, otherwise it will greatly affect the operating efficiency of PHP.

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 implementing them using C extensions.

41. Evaluate and 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.

42. mod_zip can be used as an Apache module to instantly compress your data and reduce data transmission volume by 80%.

43. 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! file_get_contents does not need to determine whether the file handle is opened successfully. But pay attention to the PHP version problem of file_get_contents when opening a URL file;

44. Try to perform as few file operations as possible, although PHP's file operation efficiency is not low;

45. Optimization Select SQL statements, and perform as few Insert and Update operations as possible (I was criticized for updating);

46. Use PHP internal functions as much as possible (but I just wanted to find A function that does not exist in PHP is a waste of time that could be used to write a custom function. It’s a matter of experience!);

47. Don’t declare variables inside the loop, especially large variables: objects (this seems like Isn’t it just a problem that needs to be paid attention to in PHP? );

48. Try not to nest nested assignments in multi-dimensional arrays;

49. When you can use PHP’s internal string manipulation functions, Don’t use regular expressions;

50. foreach is more efficient. Try to use foreach instead of while and for loops;

51. Use single quotes instead of double quotes to quote strings;

52. "Use i+=1 instead of i=i+1. It conforms to the habits of c/c++ and is more efficient";

53. For global variables, you should unset() them after use;

54. Curly brackets "{}" can operate strings like "[]" operates arrays to obtain the specified position. character.

55. The PHP tag "bb9bd6d87db7f8730c53cb084e6b4d2d" does not need to write an end tag in a stand-alone PHP script. This is to avoid unexpected spaces that cause output and cause errors. Comments can be used to indicate the end of a script.

56. Echo is a grammatical structure, not a function. When followed by multiple strings, it is more efficient to use a comma ",".

57. In the array, 1, '1', and true will be forced to be converted to 1 when they are indexes. And '01' will not be converted and will be processed as a string.

58. It is illegal to write the code of a class in different PHP tags, and a syntax error will be reported. Functions are no problem.

59. The difference and relationship between session and cookie.

The session is saved on the server, and the cookie is saved on the client's browser;

The session can be saved as a file, database, or memcached on the hard disk, and the cookie can be saved on the hard disk (persistent cookie) and memory (session cookie);

There are two ways to pass session_id, one is cookie, and the other is get method (you can specify the variable name to save session_id through the session.name configuration item).

60. Use $_SERVER['REQUEST_TIME'] instead of time() to obtain the current timestamp, which can reduce one function call and is more efficient.

61. Be careful when using _REQUEST. The priority of _REQUEST to obtain data is E(nv)G(et)P(ost)C(ookie)S(ession). If the variables have the same name, it may cause High priority data is overwritten by low priority data.

62. You must exit after the header() function, otherwise the subsequent code will still be executed.

63. Large arrays are passed by reference to reduce memory usage, and unset() is used when used.

64. Limitations of set_time_limit(). You can only limit the running time of the script itself, and cannot control the time of external execution, such as system() function, stream operation, database query, etc.

65. The difference between echo, print, print_r, var_dump and var_export:

echo and print are grammatical structures, not functions, and can only display basic types, not arrays and objects, others They are all functions, which can display arrays and objects;

echo can display multiple variables, separated by commas;

print_rThe second one Parameters can determine whether to output variables or use variables as return values;

var_dump will print the detailed information of the variables, such as length and type, and can pass multiple variables as parameters;

var_export returns legal PHP code format.

66. Verify email: filter_var($email, FILTER_VALIDATE_EMAIL);

67. How to get the file extension:

1, pathinfo( $filename), take the value of extension, or pathinfo($filename, PATHINFO_EXTENSION).

Two, end(explode('.',$filename)).

68. Try to use the ternary operator (?:);

69. Use the error_reporting(0) function to prevent potentially sensitive information from being displayed to the user.

Ideally error reporting should be completely disabled in the php.ini file. But if you are using a shared virtual host and you cannot modify php.ini, then you'd better add the error_reporting(0) function and put it on the first line of each script file (or use require_once() to load it). This can Effectively protect sensitive SQL queries and paths from being displayed when errors occur;

70. Don’t copy variables casually

Sometimes in order to make the PHP code tidier, some PHP novices (including me) ) will copy the predefined variable to a variable with a shorter name. In fact, this will double the memory consumption and will only make the program slower. Just imagine, in the following example, if the user maliciously inserts 512KB of text into the text input box, this will cause 1MB of memory to be consumed!

BAD:
$description = $_POST[&#39;description&#39;];
echo $description;
GOOD:
echo $_POST[&#39;description&#39;];

1.在可以用file_get_contents替代file、fopen、feof、fgets等系列方法的情况下,尽量用file_get_contents,因为他的效率高得多!但是要注意file_get_contents在打开一个URL文件时候的PHP版本问题; 2.尽量的少进行文件操作,虽然PHP的文件操作效率也不低的; 3.优化Select SQL语句,在可能的情况下尽量少的进行Insert、Update操作(在update上,我被恶批过); 4.尽可能的使用PHP内部函数(但是我却为了找个PHP里面不存在的函数,浪费了本可以写出一个自定义函数的时间,经验问题啊!); 5.循环内部不要声明变量,尤其是大变量:对象(这好像不只是PHP里面要注意的问题吧?); 6.多维数组尽量不要循环嵌套赋值; 7.在可以用PHP内部字符串操作函数的情况下,不要用正则表达式; 8.foreach效率更高,尽量用foreach代替while和for循环; 9.用单引号替代双引号引用字符串; 10.“用i+=1代替i=i+1。符合c/c++的习惯,效率还高”; 11.对global变量,应该用完就unset()掉; 以下是一篇关于提高PHP效率的文章 

榨干 PHP,提高效率

这篇杂文翻译整理自网络各路文档资料(见最末的参考资料),尤其是 Ilia Alshanetsky (佩服之至) 在多个 PHP 会议上的演讲,主要是各类提高 PHP 性能的技巧。为求精准,很多部分都有详细的效率数据,以及对应的版本等等。偷懒,数据就不一一给出了,直接给结论。 ======================================================== 

静态调用的成员一定要定义成 static (PHP5 ONLY)

贴士:PHP 5 引入了静态成员的概念,作用和 PHP 4 的函数内部静态变量一致,但前者是作为类的成员来使用。静态变量和 Ruby 的类变量(class variable)差不多,所有类的实例共享同一个静态变量。

QUOTE: class foo { function bar() {  echo &#39;foobar&#39;; } } $foo = new foo; // instance way $foo->bar(); // static way foo::bar();

静态地调用非 static 成员,效率会比静态地调用 static 成员慢 50-60%。主要是因为前者会产生 E_STRICT 警告,内部也需要做转换。 ======================================================== 

使用类常量 (PHP5 ONLY)

贴士:PHP 5 新功能,类似于 C++ 的 const。 使用类常量的好处是: - 编译时解析,没有额外开销 - 杂凑表更小,所以内部查找更快 - 类常量仅存在于特定「命名空间」,所以杂凑名更短 - 代码更干净,使除错更方便 ======================================================== (暂时)不要使用 require/include_once require/include_once 每次被调用的时候都会打开目标文件! - 如果用绝对路径的话,PHP 5.2/6.0 不存在这个问题 - 新版的 APC 缓存系统已经解决这个问题 文件 I/O 增加 => 效率降低如果需要,可以自行检查文件是否已被 require/include。不要调用毫无意义的函数有对应的常量的时候,不要使用函数。

QUOTE: php_uname(&#39;s&#39;) == PHP_OS; php_version() == PHP_VERSION; php_sapi_name() == PHP_SAPI;

虽然使用不多,但是效率提升大概在 3500% 左右。 最快的 Win32 检查 $is_win = DIRECTORY_SEPARATOR == '\\'; ======================================================== 

- 不用函数

- Win98/NT/2000/XP/Vista/Longhorn/Shorthorn/Whistler…通用 - 一直可用 时间问题 (PHP>5.1.0 ONLY) 你如何在你的软件中得知现在的时间?简单,「time() time() again, you ask me…」。不过总归会调用函数,慢。现在好了,用 $_SERVER[‘REQUEST_TIME’],不用调用函数,又省了。 

加速 PCRE

- 对于不用保存的结果,不用 (),一律用 (?。这样 PHP 不用为符合的内容分配内存,省。效率提升 15% 左右。 - 能不用正则,就不用正则,在分析的时候仔细阅读手册「字符串函数」部分。有没有你漏掉的好用的函数? 例如:

 strpbrk() strncasecmp() strpos()/strrpos()/stripos()/strripos()

======================================================== 

加速 strtr

如果需要转换的全是单个字符的时候,用字符串而不是数组来做

strtr:   $addr = strtr($addr, "abcd", "efgh"); // good $addr = strtr($addr, array(&#39;a&#39; => &#39;e&#39; ,//..)); // bad

效率提升:10 倍。 ======================================================== 

不要做无谓的替换

即使没有替换,str_replace 也会为其参数分配内存。很慢!解决办法: - 用 strpos 先查找(非常快),看是否需要替换,如果需要,再替换 效率: - 如果需要替换:效率几乎相等,差别在 0.1% 左右。 - 如果不需要替换:用 strpos 快 200%。 ======================================================== 

邪恶的 @ 操作符

不要滥用 @ 操作符。虽然 @ 看上去很简单,但是实际上后台有很多操作。用 @ 比起不用 @,效率差距:3 倍。 特别不要在循环中使用 @,在 5 次循环的测试中,即使是先用 error_reporting(0) 关掉错误,在循环完成后再打开,都比用 @ 快。 ======================================================== 

善用 strncmp

当需要对比「前 n 个字符」是否一样的时候,用 strncmp/strncasecmp,而不是 substr/strtolower,更不是 PCRE,更千万别提 ereg。strncmp/strncasecmp 效率最高(虽然高得不多)。 慎用 substr_compare (PHP5 ONLY),按照上面的道理,substr_compare 应该比先 substr 再比较快咯。答案是否定的,除非: - 无视大小写的比较 - 比较较大的字符串 不要用常量代替字符串 为什么: - 需要查询杂凑表两次 - 需要把常量名转换为小写(进行第二次查询的时候) - 生成 E_NOTICE 警告 - 会建立临时字符串 效率差别:700%。 ======================================================== 

不要把 count/strlen/sizeof 放到 for 循环的条件语句中

贴士:一个经典做法

QUOTE: for ($i = 0, $max = count($array);$i < $max; ++$i); ?>

效率提升相对于: - count 50% - strlen 75% ======================================================== 

短的代码不一定快

// longest if ($a == $b) { $str .= $a; } else { $str .= $b; } // longer if ($a == $b) { $str .= $a; } $str .= $b; // short $str .= ($a == $b ? $a : $b);

  你觉得哪个快? 效率比较:

 - longest: 4.27 - longer: 4.43 - short: 4.76

不可思议?再来一个:

  // original $d = dir(&#39;.&#39;); 
  while (($entry = $d->read()) !== false) { if ($entry == &#39;.&#39; || $entry == &#39;..&#39;) { continue; } } 
  // versus glob(&#39;./*&#39;); 
  // versus (include . and ..) scandir(&#39;.&#39;);

  哪个快? 效率比较: - original: 3.37 - glob: 6.28 - scandir: 3.42 - original without OO: 3.14 - SPL (PHP5): 3.95 画外音:从此也可以看出来 PHP5 的面向对象效率提高了很多,效率已经和纯函数差得不太多了。 ======================================================== 

提高 PHP 文件访问效率

需要包含其他 PHP 文件的时候,使用完整路径,或者容易转换的相对路径。  

include &#39;file.php&#39;; // bad approach incldue &#39;./file.php&#39;; // good include &#39;/path/to/file.php&#39;; // ideal

======================================================== 

物尽其用

PHP 有很多扩展和函数可用,在实现一个功能的之前,应该看看 PHP 是否有了这个功能?是否有更简单的实现?  

$filename = "./somepic.gif"; 
$handle = fopen($filename, "rb"); 
$contents = fread($handle, filesize($filename)); 
fclose($handle); // vs. much simpler file_get_contents(&#39;./somepic.gif&#39;);

  ======================================================== 

关于引用的技巧

引用可以: - 简化对复杂结构数据的访问 - 优化内存使用  

$a[&#39;b&#39;][&#39;c&#39;] = array(); 
// slow 2 extra hash lookups per access for ($i = 0; $i < 5; ++$i) $a[&#39;b&#39;][&#39;c&#39;][$i] = $i; 
// much faster reference based approach $ref =& $a[&#39;b&#39;][&#39;c&#39;]; for ($i = 0; $i < 5; ++$i) $ref[$i] = $i; ?> $a = &#39;large string&#39;; 
// memory intensive approach function a($str){ return $str.&#39;something&#39;; }
 // more efficient solution function a(&$str){ $str .= &#39;something&#39;; }   
Aug 25th, 2009
Comments

The above is the detailed content of Introduction to efficiency improvement and optimization methods in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn