53 details of PHP code optimization

  • 2021-01-14 05:46:58
  • OfStack

It is faster to use single quotes instead of double quotes to contain strings. Because PHP will search for variables in a string surrounded by double quotes, single quotes will not. Note: Only echo can do this. It is a "function" that can take multiple strings as arguments.
1. If you can define a class's methods as static, try to define them as static. It will be nearly four times faster.
$row['id'] is 7 times faster than $row[id].
3. echo is faster than print and uses multiple arguments of echo instead of string concatenation, such as echo $str1,$str2.
4. Determine the maximum number of cycles before performing the for cycle. It is better to use foreach instead of calculating the maximum number every cycle.
5, Log out those unused variables, especially large arrays, in order to free memory.
Try to avoid __get, __set, __autoload.
7, require_once() is expensive.
8, Try to use the absolute path for include files, because it avoids the speed of PHP to find the file in include_path, and the time required to parse the operating system path will be less.
9. If you want to know when the script starts to execute, use $_SERVER[' REQUEST_TIME'] rather than time().
Functions do the same thing instead of regular expressions.
11, The str_replace function is faster than the preg_replace function, but the strtr function is 4 times more efficient.
12. If a string replacement function accepts an array or a character as an argument, and the argument length is not too long, then consider writing an additional substitution code that passes one character at a time, rather than just writing one line of code that accepts an array as a query and replacement argument.
13. It is better to use select branch statements than to use multiple if, else and if statements.
14. Masking error messages with @ is very inefficient, very inefficient.
15. Open the mod_deflate module of apache to improve the browsing speed of the web page.
16, the database connection when the use should be closed, do not use long connection.
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 increasing a local variable.
20, increment 1 object attribute (e.g., $this-) > prop++) is 3 times slower than incrementing a local variable.
21. Incrementing an undefined local variable is 9-10 times slower than incrementing a predefined local variable.
22. Defining only one local variable without calling it in a function also slows things down (by the same amount as incrementing one local variable). PHP probably checks to see if global variables exist.
Method calls appear to be independent of the number of methods defined in the class, since I added 10 methods (both before and after testing the methods) with no performance change.
A method in a derived class runs faster than the same method defined in a base class.
25. Calling an empty function with one argument takes the same amount of time as performing 7-8 local variable increments. A similar method call takes close to 15 local variable increment operations.
26. Apache parses an PHP script 2 to 10 times slower than 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 set of PHP caching mechanisms usually improves performance by 25 to 100 percent, eliminating compilation overhead.
28, try to do the cache, can use memcached. memcached is a high-performance memory object caching system designed to speed up dynamic Web applications and reduce database load. The caching of operand codes (OP code) is useful so that scripts do not have to be recompiled on every request.
29. When manipulating a string and needing to verify that its length meets a certain requirement, you would naturally use the strlen() function. This function executes fairly quickly because it does not do any calculations and only returns known string lengths stored in zval structures (C's built-in data structures for storing PHP variables). However, since strlen() is a function, it is somewhat slower because the function call goes through a number of steps, such as lowercase, hash lookup, and follows function 1 as it is called. In some cases, you can use the isset() technique to speed up the execution of your code.
(Examples are as follows)
if (strlen($foo) < 5) {echo "Foo is too short" $$}
(Compare this to 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 a language construct, meaning that its execution does not require function lookups and lowercase letters. That is, you don't really spend much overhead in the top-level code that verifies the length of the string.
34, When incrementing or decrementing $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 it to be instantly faster, it will not work. ++$i is faster because it requires only three instructions (opcodes), whereas $i++ requires four instructions. Postincrement actually produces a temporary variable, which is then incremented. The preceding increment increments the original value directly. This is one of the optimizations, as is done by the PHP optimizer for Zend. It's a good idea to keep this optimization in mind, because not all instruction optimizers do the same optimization, and there are plenty of Internet service providers (ISPs) and servers that do not have an instruction optimizer installed.
35, is not necessarily object-oriented (OOP), object-oriented tends to be expensive, each method and object call will consume a lot of memory.
It is not necessary to use classes to implement all data structures. Arrays are also useful.
37. Don't break methods down too much. Think about what code you really want to reuse.
38. You can always break code into methods when you need to.
39, Try to use a large number of PHP built-in functions.
40. If you have a lot of time-consuming functions in your code, consider implementing them as extensions to ES140en.
41, Evaluation Verify (profile) your code. The validator tells you which parts of the code are taking up how much time. The Xdebug debugger includes validation programs that, in general, can show bottlenecks in your code.
42, mod_zip can be used as the Apache module, used to compress your data instantly, and can reduce the 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! Note that file_get_contents is a version of PHP when opening a single URL file.
44, as little as possible for file operation, although PHP file operation efficiency is not low;
45, Optimize Select and SQL statements to minimize Insert and Update operations if possible (I was criticized on update);
46, Use PHP internal functions as much as possible (but I wasted time when I could have written a custom function in order to find a function that does not exist in PHP). ;
47, Do not declare variables inside a loop, especially large variables: objects (PHP). ;
48, multidimensional array as far as possible do not loop nested assignment;
49. Do not use regular expressions when you can use string manipulation functions within PHP;
50, foreach is more efficient, try to replace while and for cycle with foreach;
51. Use single quotation marks instead of double quotation marks to quote strings;
52, "Replace i=i+1 with i+=1. In line with c/c++ habit, high efficiency ";
53, For global variables, unset() should be used;

Finally, the following common and important php optimization strategies are summarized:

1. Use absolute paths in includes and requires so that less time is spent analyzing paths;
$For($x=0; $x=0; $x < count($array); $x), count();
3. Use the function error_reporting(0) to prevent potentially sensitive information from being displayed to the user. Ideally error reporting should be completely disabled in the php.ini file. However, if you are using a shared virtual host, php. ini, which you cannot modify, you are better off adding the error_reporting(0) function on the first line of each script file (or load it with require_once()). This will effectively protect sensitive SQL queries and paths from being displayed in case of errors;
4. Do not allow too many loops within loops. Nesting too many loops will slow down the execution efficiency
5. Do not execute related queries inside a loop unless you absolutely have to
6. Use single quotes to join strings whenever possible
7. Reduce variable copy operations as much as possible. $description = $_POST['description'];
8. When if/else is excessive, use switch/case instead of if/else whenever possible. Can make the code more concise
9. Enabling caching helps improve performance while reducing MySQL load
10. Start gzip compression

Related articles: