In-depth analysis of PHP optimization and considerations _php Skills

Source: Internet
Author: User
Tags autoload arrays pear php code php script sql injection switch case zend

1. Try to be static:

If a method can be static, then declare it static, speed can be increased by 1/4, even when I test, this improved nearly three times times.

Of course, this test method needs to be performed above level 100,000, the effect is obvious.

In fact, the efficiency of static and Non-static methods is mainly different in memory: static methods generate memory at the beginning of the program, the instance method generates memory in the running of the program, so the static method can be called directly, the instance method genetic the instance first, and the method is called by the instance, the static speed is very fast, but it takes up more memory.

Any language is the operation of memory and disk, as to whether object-oriented, but the software layer of the problem, the bottom is the same, but the implementation of different methods. Static memory is continuous because it is generated at the start of the program, and the instance requests discrete space, so of course there is no static method fast.

Static methods always call the same memory, the disadvantage of which is that it cannot be destroyed automatically, but instantiation can be destroyed.

2.echo is more efficient than print because Echo does not return a value, and print returns an integral type;

Test:

Echo
0.000929-0.001255 s (average 0.001092 seconds)
Print
0.000980-0.001396 seconds (average 0.001188 seconds)

The difference is about 8%, and the echo is relatively fast in general.

Note that when the echo large string is not adjusted, it seriously affects performance. Use the open apached mod_deflate to compress or open ob_start first to place the content in the buffer.

3. Set the maximum number of cycles before the loop, not in the loop;

A fool can understand the truth.

4. Destroy the variable to release the memory, especially the large array;

Arrays and objects in PHP are particularly occupied by memory, which is caused by the Zend engine of PHP's underlying

In general, the PHP array memory utilization is only 1/10, that is, a C language inside the 100M memory array, in PHP will be 1G.

Especially in the system of PHP as a background server, often the problem of memory consumption is too big.

5. Avoid using magic methods such as __get, __set, __autoload, etc.

The functions that begin with __ are named Magic Functions, which are first visited under certain conditions. In total, there are a few magic functions

__construct(),__destruct(),__get(),__set(),__unset(),__call(),__callStatic(),__sleep(),__wakeup(),__toString(),__set_state(),__clone(),__autoload()

In fact, if __autoload can't efficiently match the class name to the actual disk file (note, this refers to the actual disk file, not just the filename), the system will have to do a lot of file existence (need to be found in the path included in each include path) To determine if a file exists that requires disk I/O operations, it is well known that disk I/O operations are inefficient, so this is why the autoload mechanism is less efficient.

Therefore, when designing a system, we need to define a clear mechanism for mapping the class name to the actual disk file. The simpler and clearer the rule, the more efficient the autoload mechanism is.

Conclusion: The autoload mechanism is not natural inefficiency, only the misuse of AutoLoad, the design of a bad automatic loading function will lead to the reduction of efficiency.

So try to avoid using __autoload magic method, it is debatable.

6.requiere_once () compared with resource consumption;

This is because requiere_once needs to judge whether the file is referenced or not, so you don't have to use it as much as possible. Common require/include methods are avoided.

7. Use absolute paths in includes and requires.

If you include a relative path, PHP iterates through the lookup file inside the include_path.

This type of problem is avoided with an absolute path, so it takes less time to parse the operating system path.

8. If you need to get the time when the script executes, $_server[' Requset_time '] is better than times ();
can imagine. One is ready to be used directly, and one that requires a function to produce results.

9. Can use PHP internal string operation function case, use them as much as possible, do not use regular expression, because its efficiency is higher than regular;
not to say, is the most consumption of performance.

Is there a useful function you missed? For example: Strpbrk () strncasecmp () Strpos ()/strrpos ()/stripos ()/strripos () acceleration STRTR If you need to convert all of the individual characters,
Use a string instead of an array to do STRTR:

<?php
$addr = STRTR ($addr, "ABCD", "EFGH");//good
$addr = Strtr ($addr, Array (' A ' => ' e ',));//Bad
? & Gt

Efficiency improvement: 10 times times.

10.str_replace character Substitution Buzheng replaces preg_replace fast, but STRTR is 1/4 faster than str_replace;

And don't make unnecessary substitutions. Str_replace also allocates memory for its parameters, even if there is no replacement. It's slow! Solution:
Use Strpos to find (very fast) to see if you need to replace and, if necessary, replace efficiency:-If you need to replace: the efficiency is almost equal, the difference is about 0.1%.
If you do not need to replace: Use Strpos fast 200%.

11. parameter is a string

If a function can accept an array and accept a simple character as a parameter, such as a character substitution function, and the argument list is not too long, consider writing an extra paragraph of substitution code so that each pass argument is a character, rather than accepting the array as a lookup and substitution parameter. The,1+1>2; of the punches

12. It is best not to use @, with @ To cover up errors will reduce the speed of the script;

There are many actions in the background with @ actually. Use @ compared to the @, efficiency gap: 3 times times. In particular, do not use @ in the loop, in 5 cycles of testing, even if the first with error_reporting (0) to turn off the error, after the loop is completed and then open, than the @ faster.

$row [' ID '] is 7 times times faster than $row[id]

It is recommended to develop the habit of adding quotation marks to array keys;

14. Do not use functions in the loop

For example, for ($x =0; $x < count ($array); $x), the count () function is evaluated out first; you know why.

16. Building local variables in the class method is the fastest and almost as fast as calling local variables in the method;

17. The establishment of a global variable is twice times slower than the local variable;

Because the local variables are in the stack, when a function occupies the stack space is not very large, this part of memory is likely to hit the cache, the CPU access efficiency is very high.
Conversely, if a function uses both global variables and local variables, then the CPU cache needs to switch back and forth when the two segments are significantly different, then the efficiency will decrease.
(I understand.)

18. Creating an Object attribute (a variable within a class), such as ($this->prop++), is 3 times times slower than a local variable;

19. Creating an undeclared local variable is 9-10 times slower than a local variable that has already been defined

20. Declaring a global variable that has not been used by any one function can also degrade performance (as with declaring the same number of local variables).
PHP may check to see if the global variable exists;

21. The performance of a method is not related to the number of methods defined within a class

Because I add 10 or more methods to the test class (these methods before and after the test method) there is no difference in performance;

22. The performance of the method in subclasses is superior to that in the base class;

23. A function that calls only one parameter and the function body is empty is equal to 7-8 times $localvar++ operation, while a similar method (the function in the class) runs equal to about 15 times $localvar++ operations;

24 It is quicker to use single quotes instead of double quotes to contain strings.
Because PHP searches for variables in a string enclosed in double quotes, single quotes do not.

The PHP engine allows the use of single and double quotes to encapsulate string variables, but there is a big difference! A string that uses double quotes tells the PHP engine to first read the string, find the variable, and change to the value of the variable. In general, strings are not variable, so using double quotes can lead to poor performance. It's best to use words

string concatenation instead of double quote strings.

Bad:
$output = "It is a plain string";
Good:
$output = ' 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 quicker to use commas instead of dot connectors when the echo string.

Echo is a "function" that can take multiple strings as arguments, saying that ECHO is a language structure, not a real function, and that it adds double quotes to the function.
For example, Echo $str 1, $str 2.

26.Apache Parsing a PHP script is 2 to 10 times times slower than parsing a static HTML page.

Use static HTML pages as much as possible and use less scripting.

28. Use the cache as much as possible, suggest using memcached.

High-performance distributed memory object caching system improves the performance of dynamic network application and reduces the burden of database;
It is also useful for the caching of the Operation Code (OP code) so that the script does not have to recompile for each request.

29. Use the Ip2long () and LONG2IP () functions to convert the IP address into an integer to be stored in the database instead of the character type.

This can reduce storage space by almost 1/4. At the same time, the address can be easily sorted and quickly searched;

30. Use CHECKDNSRR () to confirm the validity of part of email address through the existence of domain name

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

31. Use of mysql_* modified function mysqli_*;

32. Try to like using ternary operators (?:);

33. Do you need pear

Before you want to redo your project thoroughly, see if pear has anything you need. Pear is a huge repository of resources that many PHP developers know about;

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

The ideal error report should be completely disabled in the php.ini file. But if you're using a shared virtual host, php.ini you can't modify it, then you'd better add the error_reporting (0) function and place it in the first line of each script file (or
Require_once () to load) This effectively protects sensitive SQL queries and paths from being displayed when errors occur;

36. Use Gzcompress () and gzuncompress () to compress (extract) a large-capacity string () when saving (fetching) the database.

This built-in function uses the GZIP algorithm to compress to 90%;

37. A function can have multiple return values by reference to the parameter variable address.

You can add a "&" in front of the variable to indicate delivery by address rather than by value;

38. Fully understand the dangers of magic references and SQL injection.

Fully understand "magic quotes" and the dangers of SQL injection. I ' m hoping that most developers reading the are already with SQL familiar. However, I list it here because it's absolutely critical to understand. If you have ' ve never heard the term before, spend the entire rest of the day Googling and reading.

39. Some places use isset instead of strlen

When you manipulate strings and need to verify that their lengths meet certain requirements, you will of course use the strlen () function. This function executes fairly quickly because it does not do any calculations and returns only the known string lengths stored in the Zval structure (c's built-in data structure for storing PHP variables). However, since strlen () is a function, it will be somewhat slower, because function calls go through a number of steps, such as lowercase letters, PHP is case-insensitive, and hash lookups follow the functions that are called. In some cases, you can use the isset () technique to speed up the execution of your code.
(Examples below)

if (strlen($foo) < 5) { echo “Foo is too short”$$ }

(compare with 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 () as a language structure means that its execution does not require function lookup and lowercase. That is, you're actually not spending too much on the top-level code that verifies the length of the string.

40. Use + + $i increment


When incrementing or decrementing the value of the variable $i + + happens to be a tad slower then + + $i. This is something PHP specific and does don't 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 OpCo Des used for $i + + you only need 3. Post incrementation actually causes in the creation of a temporary var this is then incremented. While Preincrementation increases the original value directly. This is one of the 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 On and there are plenty of ISPs and servers running without a opcode optimizer.

$i + + $i slower than + + when the execution variable $i is incremented or decremented. 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 quickly become useless. + + $i faster because it requires only 3 instructions (opcodes), $i + + requires 4 instructions. A post increment actually produces a temporary variable, which is then incremented. And the predecessor increment increases directly on the original value. This is one of the most optimized processes, as Zend's PHP optimizer has done. Keeping this optimization in mind is a good idea, because not all command optimizer will do the same optimization, and there is a large number of Internet services without assembly instruction Optimizer
Providers (ISPs) and servers.

40. Do not copy the variables randomly

Sometimes in order to make the PHP code cleaner, some novice PHP (including me) will copy the predefined variables to a shorter name variable, in fact, the result is to increase the amount of memory consumption, only to make the program more slow. Imagine that in the following example, if the user maliciously inserts a 512KB byte of text into the text input box, this will result in 1MB of memory consumption!

Bad:

$description = $_post[' description '];

echo $description;

Good:

echo $_post[' description '];

41 using the Select Branch statement

Switch case is better than using multiple if,else if statements, and the code is easier to read and maintain.

42. File_get_contents can be used instead of file, fopen, feof, fgets

In the case of using file_get_contents instead of file, fopen, feof, fgets, and so on, use file_get_contents as much as possible, because of his high efficiency! But pay attention to file_get_contents in opening a URL file when the PHP version problem;

43. As little as possible file operation, although the PHP file operation efficiency is not low;

44. Optimize select SQL statements, as little as possible in the case of INSERT, update operations (on the update, I was a bad batch);

45. Use PHP internal functions as much as possible

46. Do not declare variables inside the loop, especially large variables: objects

(This seems to be not just a matter of note in PHP?) );

47. Multidimensional arrays as far as possible not to cycle nested assignment;

48.foreach more efficient, try to use foreach instead of while and for loops;

49. "Replace I=i+1 with I+=1." In line with C + + habits, efficiency is also high ";

50. For global variables, should be used up on the unset () off;

51 is not something that must be object-oriented (OOP), object-oriented is often expensive, each method and object invocation consumes a lot of memory.

52 do not subdivide the method too much, think carefully about what you really want to reuse the code?

53 If there are a lot of time-consuming functions in your code, you might consider implementing them in C-extension mode.

54, open the Apache mod_deflate module, you can improve the browsing speed of the Web page.
(referred to the question of the echo large variable)

55, the database connection should be turned off when use is finished, do not use long connection.

56, split faster than Exploade

Split ()

0.001813-0.002271 seconds (avg 0.002042 seconds)

explode () 0.001678-0.003626 seconds

(avg 0.00265 2 seconds)

Split can take regular expressions as delimiters, and runs faster. Too on ~23%.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.