Optimize PHP efficiency and some methods to improve PHP performance_PHP tutorial

WBOY
Release: 2016-07-21 15:31:35
Original
846 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! However, please pay attention to the PHP version problem of file_get_contents when opening a URL file;
2. Conduct file operations as little as possible, although PHP’s file operation efficiency is not low;
3. Optimize the Select SQL statement, where possible Under the circumstances, perform as few Insert and Update operations as possible (I was criticized for updating);
4. Use PHP internal functions as much as possible (but I wasted a lot of money trying to find a function that does not exist in PHP) It would have taken less time to write a custom function, a matter of experience!);
5. Do not declare variables inside the loop, especially large variables: objects (this seems to be not just a problem in PHP, right?);
6. Try not to loop nested assignments in multi-dimensional arrays;
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 replaces 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 more efficient." ;
11. Global variables should be unset()ed after use;
12. In for or foreach, use $tempArray[] = $field instead of $tempArray[count($tempArray)] = $ field
13. Members that are statically called must be defined as static (PHP5 ONLY)
Tips: PHP 5 introduces the concept of static members, which have the same function as static variables inside functions of PHP 4, but the former is used as a class members to use. Static variables are similar to Ruby's class variables. All instances of a class share the same static variable.

QUOTE:

Copy code The code is as follows:

// PHP CODE Highliting for CU by dZ902
class foo {
function bar() {
echo 'foobar';
}
}
$foo = new foo;
// instance way
$foo->bar();
// static way
foo::bar();
?>

statically calls non Static members are 50-60% slower than calling static members statically. Mainly because the former will generate an E_STRICT warning and needs to be converted internally.
Use class constants (PHP5 ONLY)
Tip: PHP 5 new feature, similar to C++’s const.
The benefits of using class constants are:
- Compile-time resolution, 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
- the code is cleaner and makes debugging easier
(temporarily) don’t use require/include_once
require/include_once will open the target file every time it is called!
- If absolute paths are used, this problem does not exist in PHP 5.2/6.0
- The new version of the APC cache system has solved this problem
File I/O increased => efficiency decreased
If necessary, You can check whether the file has been require/included yourself.
Don’t call meaningless functions
Don’t use functions when there are corresponding constants.
QUOTE:
Copy code The code is as follows:

// PHP CODE Highliting for CU by dZ902
< ;?php
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
QUOTE:
Copy code The code is as follows:

// PHP CODE Highliting for CU by dZ902
$is_win = DIRECTORY_SEPARATOR == '\';
?>

Time issue (PHP>5.1.0 ONLY)
Use system variable $_SERVER['REQUEST_TIME'] instead of system function time()
Accelerate PCRE

This way PHP does not need to allocate memory for matching content, saving. 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()
Accelerate strtr
If all that need to be converted are single When character, use string instead of array to do strtr:
QUOTE:
Copy code The code is as follows:

// PHP CODE Highliting for CU by dZ902
$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 replacement is needed. If necessary, replace again
Efficiency:
- If replacement is needed: The efficiency is almost equal, the difference is about 0.1%.
- If no substitution is required: 200% faster with strpos.
The evil @ operator
Don’t abuse the @ operator. Although @ looks simple, there are actually a lot of 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, not to mention PCRE, and never mention ereg. strncmp/strncasecmp is the most efficient (although not by much).
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

Don’t replace strings with constants
Why:
- Requires query hashes Table twice
- constant names need to be converted to lowercase (when performing the second query)
- E_NOTICE warning is generated
- 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
QUOTE:
Copy code The code is as follows:

// PHP CODE Highliting for CU by dZ902
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
QUOTE:
Copy code The code is as follows:

// PHP CODE Highliting for CU by dZ902
// 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 quick?
Efficiency comparison:
- longest: 4.27
- longer: 4.43
- short: 4.76
Incredible? Here's another one:
QUOTE:
Copy code The code is as follows:

// PHP CODE Highliting for CU by dZ902
// 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 : It can also be seen from this 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.
QUOTE:
Copy code The code is as follows:

// PHP CODE Highliting for CU by dZ902
< ;?php
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 see if PHP has this function? Is there a simpler implementation?
QUOTE:
Copy code The code is as follows:

// PHP CODE Highliting for CU by dZ902
< ;?php
$filename = "./somepic.gif";
$handle = fopen($filename, "rb");
$contents = fread($handle, filesize($filename)) ;
fclose($handle);
// vs. much simpler
file_get_contents('./somepic.gif');
?>

About quotes Tips for
citations can:
- Simplify access to complex structured data
- Optimize memory usage

QUOTE:
Copy code The code is as follows:

// PHP CODE Highliting for CU by dZ902
$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;
?>

QUOTE:
复制代码 代码如下:

// PHP CODE Highliting for CU by dZ902
$a = 'large string';
// memory intensive approach
function a($str)
{
return $str.'something';
}
// more efficient solution
function a(&$str)
{
$str .= 'something';
}
?>

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/323008.htmlTechArticle1、在可以用file_get_contents替代file、fopen、feof、fgets等系列方法的情况下,尽量用 file_get_contents,因为他的效率高得多!但是要注意file_get_c...
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!