Home > Backend Development > PHP Tutorial > Experience in optimizing development environment Summary of PHP execution speed optimization techniques

Experience in optimizing development environment Summary of PHP execution speed optimization techniques

WBOY
Release: 2016-07-29 08:37:25
Original
997 people have browsed it

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. Optimize the SELECT SQL statement and try to do as much as possible Do less INSERT and UPDATE operations (I was criticized for UPDATE);
4. Use PHP internal functions as much as possible (but in order to find a function that does not exist in PHP, I wasted money and could have written one. The time to customize functions is a matter of experience!);
5. Do not declare variables inside loops, especially large variables: objects (this seems to be not only a problem in PHP, right?);
6. Try not to loop multi-dimensional arrays Nested assignment;
7. Do not use regular expressions when you can use PHP’s internal string manipulation functions;
8. foreach is more efficient, try to use foreach instead of while and for loops;
9. Use single quotes instead Double quotes quote strings;
10. Use i+=1 instead of i=i+1. It conforms to the habits of c/c++ and is highly efficient;
11. For global variables, they should be unset()ed after use;
Members called statically must be defined as static (PHP5 ONLY)
Tips: PHP5 introduces static members The concept and function are the same as the internal static variables of PHP4 functions, 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 parsing, no extra 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
- Code Cleaner and easier to debug
(temporarily) do not use 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
Increased file I/O => Reduced efficiency
If necessary, you can check whether the file has been required /include.
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 function required
- Win98/NT/2000/XP/Vista/Longhorn/Shorthorn/Whistler... Universal
-Always available
Time problem (PHP>5.1.0 ONLY)
How do you know the current time in your software? Simple, "time() time() again, you ask me...".
But the function will always be called, which is slow.
Okay now, 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 allocate memory for the matching content, which saves money. The efficiency is improved by about 15%.
- If you don’t need regular expressions, don’t use regular expressions. 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()
Accelerate strtr
If all you need to convert is a single character, use a string instead of an array. strtr:
$addr = strtr($addr, "abcd", "efgh"); // good
$addr = strtr($addr, array('a' => 'e', ​​
;
Don’t do unnecessary substitutions
Even if there is no 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 again
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.
Specially 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, and never mention ereg. strncmp/strncasecmp is the most efficient (although not much higher).
Use substr_compare with caution (PHP5 ONLY)
According to the above principle, substr_compare should be faster than substr first and then. The answer is no, unless:
- case-insensitive comparison
- compare larger strings
do not replace strings with constants
Why:
- need to query the hash table twice
- need to convert the constant name to lowercase ( When performing the second query)
- Generate E_NOTICE warning
- A temporary string will be created
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
//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 == '..') {
                                                                                                                                                                                                scandir('.');
?>
Which one is faster?
效率比较:
- original: 3.37
- glob: 6.28
- scandir: 3.42
- original without OO: 3.14
- SPL (PHP5): 3.95
画外音:从此也可以看出来 PHP5 的面向对象效率提高了很多, 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
incldue './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 see if PHP has 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 usage
$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, links to some of the developments he participated in and publications, etc.
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 good enough to make people forget to sleep and eat. It is recommended when you are sleepy in the morning or after lunch. Study it carefully or you'll forget to eat and sleep!

The above introduces the experience of optimizing the development environment and a summary of PHP execution speed optimization techniques, including the experience of optimizing the development environment. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template