PHP Performance Optimization instance sharing

Source: Internet
Author: User
Tags autoload apc pear switch case zend zend server

This article is mainly to share with you the PHP performance optimization example, this article lists a lot of points, hope to help everyone.

1. Try to be static:

If a method can be static, it is declared static, the speed can be increased by 1/4, even when I test, this improved by nearly three times times.
Of course, this test method needs to be executed at level 100,000 and above, the effect is obvious.
In fact, the efficiency of static and non-static methods are mainly different in memory: Static method to generate memory at the beginning of the program, the instance method in the program run to generate memory, so the static method can be called directly, the instance method to first genetic instance, through the instance call method, the static speed is very fast, but more will account for memory.
Any language is the operation of memory and disk, as to whether object-oriented, only the software layer of the problem, the bottom is the same, but the implementation method is different. Static memory is continuous, because it is generated at the beginning of the program, and the instance is requesting a discrete space, so of course there is no static method fast.
Static methods always call the same piece of memory, the disadvantage is that it cannot be destroyed automatically, but the instantiation can be destroyed.

2.echo is more efficient than print, because Echo has no return value, and print returns an integer type;

Test:
Echo
0.000929-0.001255 s (average 0.001092 seconds)
Print
0.000980-0.001396 seconds (average 0.001188 seconds)
A difference of about 8%, the overall echo is relatively fast.
Note that when the echo is large, the performance is severely affected if no adjustment is made. Use the mod_deflate that opens apached to compress or open Ob_start first to put the content into the buffer.

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

Fools all understand the truth.

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

Arrays and objects in PHP are particularly memory-caused by PHP's underlying Zend engine,
In general, the memory utilization of the PHP array is only 1/10, that is, a C language inside the 100M memory array, in PHP 1G is necessary.
In particular, in the system of PHP as a background server, there are often problems with memory costs too much.

5. Avoid the use of magic methods such as __get, __set, __autoload, etc. (for reference only, open to discussion );

The functions that begin with __ are named Magic Functions, which are first visited under certain conditions. In a sense, there are several magic functions
__construct (), __destruct (), __get (), __set (), __unset (), __call (), __callstatic (), __sleep (), __wakeup (), __tostring () , __set_state (), __clone (), __autoload ()

In fact, if __autoload does not efficiently match the class name to the actual disk file (note that this refers to the actual disk file, not just the file name), the system will have to do a large number of files exist (need to be found in each include path to find) judgment, It is well known that disk I/O operations are inefficient in determining if a file exists, so this is why the autoload mechanism is less efficient.

Therefore, when designing a system, we need to define a clear set of mechanisms for mapping the class name to the actual disk file. The simpler and clearer the rule, the higher the efficiency of the autoload mechanism.
Conclusion: The autoload mechanism is not a natural inefficiency, only the misuse of AutoLoad, the design of a bad automatic loading function will lead to the reduction of its efficiency.

so it is debatable to avoid using __autoload magic method as far as possible.

6.requiere_once () comparative consumption of resources;

This is because requiere_once needs to determine if the file has been referenced, so it can not be used as much as possible. Commonly used require/include methods to avoid.

7. Use absolute paths in includes and requires.

If you include a relative path, PHP will traverse the include_path to find the file.
This type of problem is avoided with absolute paths, so less time is required to resolve the operating system path.

8. $_server[' Requset_time ' is better than time () if you need to get the script to execute.

Can imagine. One is ready to use directly, and one needs the result of the function.

9. If you can use PHP internal string manipulation functions, try to use them, do not use regular expressions, because their efficiency is higher than the regular;

Not to say, 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 a single character,
Use strings instead of arrays to do STRTR:

<?PHP$ADDR = STRTR ($addr, "ABCD", "efgh"); GOOD$ADDR = STRTR ($addr, Array (' a ' = ' e ',)); Bad?>

Efficiency improvement: 10 times times.

10.str_replace character substitution singular replace preg_replace fast, but STRTR is 1/4 faster than str_replace;

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

11. The parameter is a string

If a function can accept both an array and a simple character as a parameter, such as a character substitution function, and the argument list is not too long, consider writing an additional replacement code so that each pass argument is a character, rather than accepting the array as a find and replace parameter. Punches,1+1>2;

12. It is best not to use @ to cover up the error will slow down the script run;

With @ Actually there are many operations in the background. With @ than without @, efficiency gap: 3 times times. In particular, do not use @ in the loop, in the 5-cycle test, even if the first use of error_reporting (0) to turn off the error, after the cycle is completed and then open, than with @ faster.

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

It is suggested that 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 calculated outside the first; you know why.

16. The fastest way to create local variables in a class method is almost as fast as calling local variables in a method;

17. Creating a global variable is twice times slower than local variables;

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

18. Create an object property (the variable inside the class) for example ($this->prop++) is 3 times times slower than local variables;

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

20. Declaring a global variable that is not used by any of the functions also degrades performance (as well as declaring the same number of local variables).

PHP may go to check if this global variable exists;

21. The performance of the 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) performance is no different;

22. The performance of the method in the subclass is better than that in the base class;

23. Only one parameter is called and the function that is empty is equal to 7-8 $localvar++ operations, and a similar method (function in class) runs equal to approximately 15 $localvar++ operations;

24 Use single quotes instead of double quotes to include strings, which is faster.

Because PHP searches for a variable in a string surrounded by double quotes, the single quotation mark does not.

The PHP engine allows the use of single and double quotes to encapsulate string variables, but this is a big difference! A string using double quotes tells the PHP engine to first read the string contents, look for the variable in it, and change the value to the variable. Generally speaking, strings are not variable, so using double quotes can cause poor performance. It is best to use the word
String concatenated instead of double-quoted strings.

Bad: $output = "The 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. Use commas instead of point connectors when echo strings are faster.

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 add a double quote 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 fewer scripts.

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

High-performance distributed memory object cache system, improve the performance of dynamic network applications, reduce the burden of the database;

It is also useful for caching 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 type into the database instead of the character type.

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

30. Use CHECKDNSRR () to confirm the validity of some email addresses through the presence of a domain name

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

31. Using the modified function of mysql_* mysqli_*;

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

33. Do I need to pear

Before you want to completely re-do your project, see if Pear has anything you need. Pear is a huge repository of resources that many PHP developers know;

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. However, if you are using a shared virtual host, php.ini you can not modify, then you'd better add error_reporting (0) function, put in the first line of each script file (or with

Require_once () to load) This can effectively protect sensitive SQL queries and paths from being displayed when errors occur;

36. Use Gzcompress () and gzuncompress () to compress (decompress) the large-capacity string when the database is stored in (out).

This built-in function can be compressed to 90% using the GZIP algorithm;

37. Make a function have multiple return values by referring to the argument variable address.

You can add a "&" to the variable before it is passed by address rather than by value;

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

Fully Understand "magic quotes" and the dangers of SQL injection. I ' m hoping that most developers reading this is 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.

39. Some places use isset instead of strlen

When you manipulate a string and need to verify that its length satisfies a certain requirement, you will of course use the strlen () function. This function executes quite quickly because it does not do any calculations and only returns the length of the known string stored in the Zval structure (the built-in data structure of C for storing PHP variables). However, because strlen () is a function, it is somewhat slower, because function calls go through a number of steps, such as lowercase letters (lowercase, PHP does not differentiate between function names), and hash lookups, which follow the called functions. In some cases, you can use the isset () technique to speed up execution of your code.

(for example) if (strlen ($foo) < 5) {echo "Foo is too Short"} (compared 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 lookups and lowercase letters. In other words, you're actually not spending much overhead in the top-level code that examines the length of the string.

40. Use + + $i increment

when incrementing or decrementing the value of the variable $i + + happens to bes a tad slower t Hen + + $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 I T ' ll suddenly become faster, it won ' t. + + $i happens to being faster in PHP because instead of 4 opcodes used for $i + + you only need 3. Post incrementation actually causes in the creation of a temporary var that's then incremented. While preincrementation increases the original value directly. This is one of the optimization so opcode optimized like Zend ' s PHP optimizer. It's a still a good idea to keep in mind since not all opcode optimizers perform this optimization and there are plenty O F ISPs and servers running without an opcode optimizer.

When the variable $i is incremented or decremented, $i + + will be slower $i than the + +. This difference is unique to PHP and does not apply to other languages, so please do not modify your C or Java code and expect them to become fast and useless. + + $i is faster because it requires only 3 instructions (opcodes), $i + + requires 4 instructions. The post increment actually produces a temporary variable, which is then incremented. The predecessor increment is incremented directly on the original value. This is one of the most optimized processing, as Zend's PHP optimizer did. It's a good idea to keep this optimization in mind, because not all of the instruction optimizer will do the same optimizations, and there are a lot of internet services that don't have an assembly instruction optimizer
Providers (ISPs) and servers.

40. Do not copy variables randomly

Sometimes in order to make the PHP code more neat, some novice PHP (including me) will copy the predefined variables into a shorter name of the variable, in fact, the result is an increase in memory consumption, will only make the program more slowly. Imagine, in the following example, if the user maliciously inserted 512KB bytes of text into the text input box, which will result in 1MB of memory consumption!

Bad: $description = $_post[' description '];echo $description; Good:echo $_post[' description '];

41 using the Select Branch statement

The 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 substituted for file, fopen, feof, fgets

In the case can be replaced with file_get_contents file, fopen, feof, Fgets and other series of methods, try to use file_get_contents, because his efficiency is much higher! But pay attention to the PHP version of file_get_contents when opening a URL file;

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

44. Optimize the Select SQL statement and make the INSERT and update operations as few as possible (on update, I was ill-approved);

45. Use the PHP intrinsics as much as possible

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

(This is not just a question to be aware of in PHP, is it?) );

47. Multidimensional arrays try not to loop nested assignments;

48.foreach more efficient, use foreach instead of while and for loops as much as possible;

50. For the global variable, it should be used up unset () off;

51 is not a matter of object-oriented (OOP), object-oriented tends to be expensive, and each method and object invocation consumes a lot of memory.

52 don't subdivide the method too much, think about what code you really want to reuse?

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

54, compressed output: Open Apache Mod_deflate module, can improve the browsing speed of the page.

(mention of the echo big variable problem)

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

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

The above are all about PHP code optimization, the following is the overall structure to optimize the performance of PHP:

Optimizing PHP Performance in terms of overall structure

1. Upgrade PHP to the latest version

The simplest way to improve performance is to constantly upgrade and update the PHP version.

2. Using analyzers

There are a lot of reasons why websites are slow, and Web applications are extremely complex and confusing. And one possibility lies in the PHP code itself. This parser can help you quickly find the code that is causing the bottleneck and improve the overall performance of your site's operations.

Xdebug PHP extension provides powerful features that can be used for debugging or for parsing code. Allows developers to directly track the execution of scripts, real-time view of comprehensive data. You can also import this data into the visual tool Kcachegrind.

3. Error checking report

PHP supports a powerful error-checking feature that allows you to check for errors in real time, from more important errors to relatively small running tips. A total of 13 independent reporting levels are supported, and you can generate user-defined test reports based on these levels of flexible matching.

4. Using PHP extensions

All along, we are complaining that PHP content is too complex, in recent years the developers made a corresponding effort to remove some of the redundant features of the project. Even so, the number of available libraries and other extensions is considerable. Even some developers are starting to think about implementing their own extension scenarios.

5.PHP cache, using PHP Accelerator: APC

In general, PHP scripts are compiled and executed by the PHP engine, and are converted to machine language, also known as opcode. If the PHP script has been compiled repeatedly to get the same result, why not skip the compilation process completely?

With the PHP accelerator, you can do this completely, caching the PHP script's compiled machine code, allowing the code to execute immediately as required without the tedious compilation process.

For PHP developers, there are two available caching options, APC (alternative PHP cache, optional PHP buffer), which is an open source accelerator that can be installed through pear. Another popular scenario is Zend Server, which not only provides opcode caching techniques, but also provides caching tools for the corresponding pages.

6. Memory Cache

PHP often plays an important role in retrieval and data analysis, which can lead to performance degradation. In fact, some operations are completely unnecessary, especially from the database repeatedly retrieving some commonly used static data. Consider the short-term use of Memcached extension to cache data. Memcached's extended cache works with the libmemcached library, caches data in RAM, and allows users to define the age of the cache, helping to ensure that user information is updated in real time.

7. Content Compression :

Almost all browsers support gzip compression, gzip can reduce the output of 80%, pay the price is about 10% increase in CPU calculation. But what you earn is that not only does the bandwidth decrease, but your page loads quickly and optimizes the performance of your PHP site.
You can open it in php.ini.
Zlib.output_compression = On
Zlib.output_compression_level = (level) may be a number between 1-9, you can set different numbers so that he fits your site. )
If you use Apache, you can also activate the Mod_gzip module, which he is highly customizable.

8. Server cache:

Mainly based on the Web reverse proxy static server Nginx and squid, as well as the apache2 mod_proxy and Mod_cache modules

9. Database optimization: Database Cache, etc.

By configuring the database cache, such as opening the Querycache cache, when the query receives one and the same query, the server will retrieve the results from the query cache instead of parsing and executing the last query again
As well as data stored procedures, connection pooling technology and so on.

Related recommendations:

PHP performance optimization tips for sharing

An example of PHP performance optimization

PHP Performance Optimization Tips Five

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.