Home  >  Article  >  Backend Development  >  Summary of PHP execution speed optimization techniques_PHP tutorial

Summary of PHP execution speed optimization techniques_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 15:53:44744browse

1. 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! But please pay attention to the PHP version problem of file_get_contents when opening a URL file;

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

3. Optimization SELECT SQL statements, perform as few INSERT and UPDATE operations as possible (I was criticized on UPDATE);

4. Use PHP internal functions as much as possible (but I just want 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! );

5. 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? );


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



7. You can use PHP In the case of internal string manipulation functions, do not use regular expressions;



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



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



10. Use i+=1 instead of i=i+1. It conforms to the habits of c/c++ and is highly efficient;



11. Global variables should be unset()ed after use;


are called statically Members must be defined as static (PHP5 ONLY)

Tips: PHP5 introduces the concept of static members, which has the same function as the static variables inside the function of PHP4, but the former is used as a member of the class. Static variables are similar to Ruby's class variables. All instances of a class share the same static variable. The efficiency of statically calling non-static members will be 50-60% slower than statically calling static members. Mainly because the former will generate an E_STRICT warning and needs to be converted internally.

class foo {
function bar() {
echo 'foobar';
}
}
$foo = new foo;
// instance way
$foo->bar();
// static way
foo::bar();
?>

Use class constants (PHP5 ONLY)

Tips: PHP5 new function, similar to C++ const.

The benefits of using class constants are:

- Compile-time analysis, no additional overhead

- The hash table is smaller, so internal lookups are faster

- Class constants only exist in a specific "namespace", so the hash name is shorter

- The code is cleaner, making debugging easier



(temporarily) Do not use it require/include_once

require/include_once will open the target file every time it is called!

- If you use absolute paths, PHP 5.2/6.0 does not have this problem

- The new version of the APC cache system has solved this problem

File I/O increased => ; Reduced efficiency

If necessary, you can check whether the file has been require/included.



Don’t call meaningless functions

Don’t use functions when there are corresponding constants.

php_uname('s') == PHP_OS;
php_version() == PHP_VERSION;
php_sapi_name() == PHP_SAPI;
?>
Although it is not used much, the efficiency improvement is about 3500%.



The fastest Win32 check

$is_win = DIRECTORY_SEPARATOR == '\';
?>
- No need for functions

- Win98/NT/2000/XP/Vista/Longhorn/Shorthorn/Whistler... Universal

- always available



time Question (PHP>5.1.0 ONLY)

How do you know the current time in your software? Simple, "time() time() again, you ask me...".

But it will always call the function, which is slow.

Now it’s better, use $_SERVER['REQUEST_TIME'], no need to call the function, save again.



Accelerate PCRE

- For results that do not need to be saved, do not use (), always use (?:)

In this way, PHP does not need to match the content Allocate memory, save. The efficiency is improved by about 15%.

- If you can use regular expressions, do not use regular expressions. Please read the "String Functions" section of the manual carefully when analyzing.Are there any useful functions that you missed?

For example:

strpbrk()

strncasecmp()

strpos()/strrpos()/stripos()/strripos()



Speed ​​up strtr

If all you need to convert is a single character, use a string instead of an array to do strtr:

$addr = strtr($addr, "abcd", "efgh"); // good
$addr = strtr($addr, array('a' => 'e', ​​
// . ..
                                          )); // bad
?>
Efficiency improvement: 10 times.



Don’t do unnecessary substitutions

Even without substitution, str_replace will allocate memory for its parameters. Very slow! Solution:

- Use strpos to search first (very fast) to see if it needs to be replaced. If necessary, replace

Efficiency:

- If it needs to be replaced: the efficiency is almost Equal, the difference is about 0.1%.

- If no replacement is needed: use strpos 200% faster.



The evil @ operator

Don’t abuse the @ operator. Although @ looks simple, there are actually many operations behind the scenes. The efficiency difference between using @ and not using @ is: 3 times.

Especially do not use @ in a loop. In the test of 5 loops, even if you use error_reporting(0) to turn off the error first and then turn it on after the loop is completed, it is faster than using @.



Make good use of strncmp

When you need to compare whether the "first n characters" are the same, use strncmp/strncasecmp instead of substr/strtolower, let alone PCRE. Don't even mention ereg. strncmp/strncasecmp is the most efficient (although not much higher).



Use substr_compare with caution (PHP5 ONLY)

According to the above reason, substr_compare should be faster than substr first and then. The answer is no, unless:


- Case-insensitive comparison

- Compare larger strings





Don’t use constants instead of strings

Why:

- Need to query the hash table twice

- Need to convert the constant name to lowercase (for the second query time)

- Generate E_NOTICE warning

- Will create a temporary string

Efficiency difference: 700%.





Don’t put count/strlen/sizeof in the conditional statement of the for loop

Tips: My personal approach

for ($i = 0, $max = count($array);$i < $max; ++$i);
?>
The efficiency improvement is relative to :

- count 50%

- strlen 75%



Short code is not necessarily fast


< ?php
//longest
if ($a == $b) {
$str .= $a;
} else {
$str .= $b;
}
// longer
if ($a == $b) {
$str .= $a;
}
$str .= $b;
// short
$str .= ($a == $b ? $a : $b);
?>
Which one do you think is faster?

Efficiency comparison:

- longest: 4.27

- longer: 4.43

- short: 4.76

Incredible? One more one:


// original
$d = dir('.');
while (($entry = $d->read ()) !== false) {
if ($entry == '.' || $entry == '..') {
continue;
}
}
/ / versus
glob('./*');
// versus (include . and ..)
scandir('.');
?>
Which one is faster?

Efficiency comparison:

- original: 3.37

- glob: 6.28

- scandir: 3.42

- original without OO: 3.14

- SPL (PHP5): 3.95

Voiceover: From now on, it can be seen that the object-oriented efficiency of PHP5 has been improved a lot, and the efficiency is not much different from that of pure functions.



Improve PHP file access efficiency

When you need to include other PHP files, use full paths, or relative paths that are easy to convert.

include 'file.php'; // bad approach
include './file.php'; // good
include '/path/to/file .php'; // ideal
?>


Make the best use of everything

PHP has many extensions and functions available. Before implementing a function, you should take a look Does PHP have this function? Is there a simpler implementation?

$filename = "./somepic.gif";
$handle = fopen($filename, "rb");
$contents = fread($handle , filesize($filename));
fclose($handle);
// vs. much simpler
file_get_contents('./somepic.gif');
?>





Tips about references

References can:

- Simplify access to complex structured data

- Optimize memory Use


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


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

Reference materials

http://ilia.ws

Ilia’s personal website, Blog, the development he participated in and some publications he published Links and more.

http://ez.no

eZ components official website, eZ comp is an open source universal library for PHP5, taking efficiency as its own responsibility, and Ilia also participated in the development.

http://phparch.com

php|architect, a good php publisher/training organization. If you can't afford it or can't buy it, there are many pirated copies of classics available online.

http://talks.php.net

The collection of speeches at the PHP conference is not very rich yet, but the content is all good stuff that makes people forget to eat and sleep easily. It is recommended to study it carefully in the morning when you are sleepy or after lunch, otherwise you will forget to eat and sleep!

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/318678.htmlTechArticle1. When file_get_contents can be used to replace file, fopen, feof, fgets and other series of methods, try to use file_get_contents , because he is much more efficient! But be careful about file_get_con...
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