In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article introduces the relevant knowledge of "PHP optimization methods and matters needing attention". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
1. Try to be static:
If a method can be static, declare it static, and the speed can be increased by 1 beat by 4, and even when I tested it, it was nearly tripled.
Of course, this test method needs to be executed more than 100,000 times before the effect is obvious.
In fact, the main difference between the efficiency of static methods and non-static methods lies in memory: static methods generate memory at the beginning of the program, and instance methods generate memory when the program is running, so static methods can be called directly, and instance methods need to generate instances first. through the instance to call the method, the static speed is very fast, but more will occupy memory.
Any language is the operation of memory and disk, as for whether it is object-oriented, it is only a question of the software layer, the bottom layer is the same, but the implementation methods are different. Static memory is continuous, because it is generated at the beginning of the program, and the instance applies for discrete space, so it is certainly not as fast as the static method.
Static methods always call the same block of memory, but the disadvantage is that they cannot be destroyed automatically, but can be destroyed by instantiation.
2.echo is more efficient than print because echo does not return a value and print returns an integer
Test:
Echo0.000929-0.001255 s (average 0.001092 seconds) Print0.000980-0.001396 seconds (average 0.001188 seconds)
The difference is about 8%. On the whole, echo is relatively fast.
Note that when echo is a large string, performance will be seriously affected if no adjustments are made. Use the mod_deflate that opens apached to compress or open ob_start to put the content in the buffer first.
3. Set the maximum number of cycles before the loop, not in the loop
What fools know.
4. Destroy variables to free memory, especially large arrays
Arrays and objects occupy a lot of memory in php, which is caused by the underlying zend engine of php
Generally speaking, the memory utilization of the PHP array is only 1 to 10, that is, an array with 100 megabytes of memory in the C language is 1G in PHP.
Especially in the system where PHP is used as the background server, the memory consumption is often too high.
5. Avoid using magic methods such as _ _ get, _ _ set, _ _ autoload
The functions that begin with _ _ are named magic functions, and such functions are first visited under specific conditions. All in all, there are a few magic functions
_ _ construct (), _ _ destruct (), _ _ get (), _ _ set (), _ _ unset (), _ _ call (), _ _ callStatic (), _ _ sleep (), _ _ wakeup (), _ _ toString (), _ _ set_state (), _ _ clone (), _ _ autoload ()
In fact, if _ _ autoload cannot efficiently match the class name with the actual disk file (note, here refers to the actual disk file, not just the file name), the system will have to judge whether a large number of files exist (need to be found in the path contained in each include path), and to judge whether the file exists or not, it is well known that the efficiency of disk Iandano operation is very low. Therefore, this is the reason for the inefficiency of the autoload mechanism.
Therefore, when we design the system, we need to define a clear mechanism to map the class name to the actual disk file. The simpler and clearer this rule is, the more efficient the autoload mechanism will be.
Conclusion: the autoload mechanism is not naturally inefficient. Only the abuse of autoload and the poorly designed autoloading function will lead to the decrease of its efficiency.
Therefore, it is open to question to avoid using _ _ autoload magic method as far as possible.
6.requiere_once () consumes more resources.
This is because requiere_once needs to determine whether the file has been referenced), so you don't have to try not to use it. Require/include method is commonly used to avoid.
7. Use absolute paths in includes and requires.
If a relative path is included, PHP will traverse the include_path to find the file.
Using absolute paths avoids such problems, so it takes less time to resolve operating system paths.
8. If you need to get the time of script execution, $_ SERVER ['REQUSET_TIME'] is better than time ()
I can imagine. One is ready-to-use, and the other is a result that needs to be obtained by a function.
9. If you can manipulate functions with PHP internal strings, try to use them instead of regular expressions, because they are more efficient than regular expressions
Needless to say, regularization consumes the most performance.
Are there any useful functions that you missed? For example: strpbrk () strncasecmp () strpos () / strrpos () / stripos () / strripos () accelerate strtr if all you need to convert is a single character
Strtr with a string instead of an array:
Efficiency improvement: 10 times.
10.str_replace character substitution is faster than regular replacement preg_replace, but strtr is faster than str_replace.
Also, don't do unnecessary replacements. even if there is no replacement, str_replace allocates memory for its parameters. Very slow! Solution:
Use strpos to find first (very quickly) to see if you need to replace, and if so, replace efficiency:-if you need to replace: the efficiency is almost equal, the difference is about 0.1%.
If you don't need a replacement: use strpos 200% faster.
11. Parameter is a string
If a function can accept both arrays and simple characters as parameters, such as a character replacement function, and the parameter list is not too long, consider writing an additional replacement code so that each pass parameter is one character, instead of accepting an array as a find and replace parameter. Make a big deal small, 1: 1 > 2
twelve。 It's best not to use @. Masking errors with @ will slow down the script.
There are actually a lot of operations in the background with @. The efficiency gap between using @ and not using @ is 3 times. In particular, do not use @ in a loop. In a five-loop test, it is faster than using @ to turn off the error with error_reporting (0) and then turn it on after the loop is complete.
13.$row ['id'] is seven times faster than $row [id].
It is recommended to form the habit of adding quotation marks to array keys.
14. Don't use functions in loops
For example, For ($xan0; $x
< count($array); $x), count()函数在外面先计算;原因你懂的。 16.在类的方法里建立局部变量速度最快,几乎和在方法里调用局部变量一样快; 17.建立一个全局变量要比局部变量要慢2倍; 由于局部变量是存在栈中的,当一个函数占用的栈空间不是很大的时候,这部分内存很有可能全部命中cache,这时候CPU访问的效率是很高的。 相反,如果一个函数里既使用了全局变量又使用了局部变量,那么当这两段地址相差较大时,cpu cache需要来回切换,那么效率会下降。 (我理解啊) 18.建立一个对象属性(类里面的变量)例如($this->Prop++) is 3 times slower than local variables
19. Building an undeclared local variable is 9-10 times slower than a defined local variable.
20. Declaring a global variable that has not been used by any function also degrades performance (just like declaring the same number of local variables).
PHP may check to see if this global variable exists
21. The performance of methods has nothing to do with the number of methods defined in a class
Because there is no difference in performance after I add 10 or more methods to the tested class (these methods are before and after the test method)
twenty-two。 The performance of methods in subclasses is better than that in base classes.
23. A function that calls only one parameter and the function body is empty takes 7-8$ localvar++ operations, while a similar method (a function in the class) runs about 15$ localvar++ operations
24 it is faster to include strings in single quotation marks instead of double quotation marks.
Because PHP searches for variables in strings enclosed in double quotes, single quotes do not.
The PHP engine allows you to use single and double quotes to encapsulate string variables, but there is a big difference! The string in double quotes tells the PHP engine to read the string first, find the variable in it, and change it to the corresponding value of the variable. Generally speaking, strings have no variables, so using double quotes can lead to poor performance. It's best to use words.
String concatenation instead of double quotation mark string.
BAD:$output = "This is a plain string"; GOOD:$output = 'This is a plain string';BAD:$type = "mixed"; $output = "This is a $type string"; GOOD:$type =' mixed';$output = 'This is a'. $type.' String'
25. It is faster to replace dot connectors with commas when echo strings.
Echo is a "function" that can take multiple strings as arguments. The PHP manual says that echo is a language structure, not a real function, so the function is in double quotes.
For example, echo $str1,$str2.
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.
twenty-eight。 Try to use caching, but memcached is recommended.
A high-performance distributed in-memory object caching system can improve the performance of dynamic network applications and reduce the burden on databases.
It is also useful for caching operational codes (OP code) so that scripts do not have to be recompiled for each request.
twenty-nine。 Use the ip2long () and long2ip () functions to convert IP addresses into integers and store them in the database instead of characters.
This can almost reduce the storage space of 1 pound by 4. At the same time, it is easy to sort and quickly find addresses.
thirty。 Use checkdnsrr () to confirm the validity of some email addresses through the existence of domain names
This built-in function ensures that each domain name corresponds to an IP address
thirty-one。 Using the improved function mysqli_* of mysql_*
thirty-two。 Try to like using the ternary operator (?:)
thirty-three。 Is PEAR required?
Before you want to completely redo your project, see if PEAR has anything you need. PEAR is a huge repository, as many php developers know.
thirty-five。 Use the error_reporting (0) function to prevent potentially sensitive information from being displayed to the user.
Ideal 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, you'd better add the error_reporting (0) function on the first line of each script file (or use the
Require_once () to load) this effectively protects sensitive SQL queries and paths from being displayed in the event of an error
thirty-six。 Use gzcompress () and gzuncompress () to compress (decompress) large-capacity strings when storing (fetching) into (out) the database.
This built-in function can be compressed to 90% using the gzip algorithm
thirty-seven。 A function has multiple return values through a reference to the address of a parameter variable.
You can add a "&" to the variable to indicate that it is passed by address rather than by value.
thirty-eight。 Fully understand the dangers of magic quotes and SQL injections.
Fully understand "magic quotes" and the dangers of SQL injection. I'm hoping that most developers reading this are already familiar with SQL injection. However, I list it here because it's absolutely critical to understand. If you've never heard the term before, spend the entire rest of the day googling and reading.
thirty-nine。 Isset is used instead of strlen in some places
When you manipulate a string and need to verify that its length meets certain requirements, you take it for granted that you 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.
forty。 Use + $I to increment
When incrementing or decrementing the value of the variable $i happens to be faster in PHP because instead of + happens to be a tad slower then + + $I. This is something PHP specific and does not apply to other languages, so don't go modifying your C or Java code thinking it'll suddenly become faster, it won't. + + $i happens to be faster in PHP because instead of 4 opcodes used for $iota + you only need 3. Post incrementation actually causes in the creation of a temporary var that is then incremented. While preincrementation increases the original value directly. This is one of the optimization that opcode optimized like Zend's PHP optimizer. It is a still a good idea to keep in mind since not all opcode optimizers perform this optimization and there are plenty of ISPs and servers running without an opcode optimizer.
When the increment or decrement of the variable $I is performed, $ibasket + is 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 is 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 services that do not assemble instruction optimizers.
Provider (ISPs) and server.
forty。 Don't copy variables casually
Sometimes, in order to make the PHP code cleaner, some PHP novices (including me) copy predefined variables into a variable with a shorter name, which actually doubles the memory consumption and only makes the program slower. Imagine that in the following example, if the user maliciously inserts 512KB bytes of text into the text input box, this will cause 1MB's memory to be consumed!
BAD:$description = $_ POST ['description']; echo $description;GOOD:echo $_ POST [' description']
41 use a select branch statement
Switch case is better than using multiple if,else if statements, and the code is easier to read and maintain.
forty-two。 File_get_contents can be used instead of file, fopen, feof, fgets
When file_get_contents can be used instead of file, fopen, feof, fgets, etc., 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.
forty-three。 Do as little file operation as possible, although the file operation efficiency of PHP is not low.
forty-four。 Optimize Select SQL statements and do as few Insert and Update operations as possible (I was maliciously criticized on update)
forty-five。 Use PHP internal functions as much as possible
forty-six。 Do not declare 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?
forty-seven。 Try not to have cyclic nesting assignments for multidimensional arrays.
48.foreach is more efficient, using foreach instead of while and for cycles as far as possible
49. "replace i=i+1 with iTunes 1. It is in line with the habit of cUniverse plus with high efficiency."
fifty。 For the global variable, unset () should be dropped as soon as it is finished.
51 is not necessarily object-oriented (OOP), object-oriented is often very expensive, each method and object call will consume a lot of memory.
Don't break down the methods too much, think about what code you really intend to reuse?
53 if there are a large number of time-consuming functions in your code, you can consider implementing them in a C extension.
54. Open the mod_deflate module of apache to improve the browsing speed of the web page.
(mentioned the issue of large echo variables)
55. The database connection should be turned off when it is finished, and do not use a long connection.
Split is faster than exploade
Split () 0.001813-0.002271 seconds (avg 0.002042 seconds) explode () 0.001678-0.003626 seconds (avg 0.002652 seconds) Split can take regular expressions as delimiters, and runs faster too. ~ 23% on average. "PHP optimization methods and matters needing attention" is introduced here, thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
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: 231
*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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.