Some ways to optimize PHP efficiency and improve PHP performance

Source: Internet
Author: User
Tags functions glob hash new features variables php file strlen variable
1, can use file_get_contents instead of file, fopen, feof, Fgets, and other series of methods, as far as possible with file_get_contents, because his efficiency is much higher! But pay attention to file_get_contents in opening a URL file when the PHP version problem;
2, as far as possible the file operation, although the PHP file operation efficiency is not low;
3, optimize the Select SQL statements, as far as possible, as little as possible insert, update operation (in update, I was a bad batch);
4, as far as possible use of PHP internal functions (but I was in order to find a PHP does not exist in the function, wasted the time to write a custom function, experience problems AH!) );
5. Do not declare variables inside the loop, especially large variables: objects (this seems to be not just a matter of note in PHP)? );
6, multidimensional array as far as possible not to cycle nested assignment;
7, in the case of PHP internal string manipulation function, do not use regular expression;
8, foreach more efficient, as far as possible with foreach instead while and for loops;
9, the use of single quotes instead of double quotes quoted strings;
10, "Replace i=i+1 with I+=1." In line with C + + habits, efficiency is also high ";
11, to global variables, should be used up on the unset () off;
12. In the for or foreach, replace $tempArray [count ($tempArray)] with $tempArray [] = $field $field
13, static call members must be defined as static (PHP5 only)
Tip: PHP 5 introduces the concept of static members, the role of PHP 4 and the function of the internal static variables, but the former is as a member of the class to use. Static variables are similar to Ruby's class variables (class variable), and instances of all classes share the same static variable.

QUOTE:
Copy CodeThe code is as follows:
PHP CODE highliting for CU by dZ902
<?php
class Foo {
function Bar () {
Echo ' Foobar ';
}
}
$foo = new Foo;
Instance Way
$foo->bar ();
Static Way
Foo::bar ();
?>

The static invocation of a non-static member is more efficient than a static call to a static member 50-60%. Mainly because the former will produce e_strict warning, internal also need to do the conversion.
Use class Constants (PHP5 only)
Tip: PHP 5 new features, similar to C + + Const.
The benefits of using class constants are:
-Compile-time parsing with no additional overhead
-hash table is smaller, so internal lookup is faster
-Class constants exist only in a specific "namespace", so the hash name is shorter
-More clean code, make debugging more convenient
(temporarily) do not use Require/include_once
Require/include_once will open the target file every time it is invoked!
-If you use an absolute path, PHP 5.2/6.0 does not have this problem
-The new APC cache system has solved this problem
File I/O increased => efficiency reduction
If necessary, you can check whether the file has been require/include.
Do not call meaningless functions
Do not use a function when there is a corresponding constant.
QUOTE:
Copy CodeThe 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 not used much, but the efficiency improvement is about 3,500%.
The quickest Win32 check.
QUOTE:
Copy CodeThe code is as follows:
PHP CODE highliting for CU by dZ902
<?php
$is _win = Directory_separator = = ' \ ';
?>

Time problem (php>5.1.0 only)
Use system variable $_server[' request_time ' instead of system function time ()
Accelerate PCRE

This way PHP does not have to allocate memory for the content, province. Efficiency increases by about 15%.
-Can not use the regular, do not have the regular, in the analysis time carefully read the manual "String function" section. Is there a useful function you missed?
For example:
STRPBRK ()
STRNCASECMP ()
Strpos ()/strrpos ()/stripos ()/strripos ()
Accelerate STRTR
If you need to convert all of a single character, use a string instead of an array to do STRTR:
QUOTE:
Copy CodeThe code is as follows:
PHP CODE highliting for CU by dZ902
<?php
$ADDR = STRTR ($addr, "ABCD", "efgh"); Good
$ADDR = STRTR ($addr, Array (' A ' => ' e '),
// ...
)); Bad
?>

Efficiency improvement: 10 times times.
Don't make unnecessary substitutions.
Even if there is no substitution, str_replace allocates memory for its parameters. It's slow! Solution:
-Use Strpos to find (very fast) to see if you need to replace, if necessary, replace
Efficiency:
-If you need to replace: the efficiency is almost equal, the difference is about 0.1%.
-If no replacement is needed: Use Strpos fast 200%.
The Evil @ operator
Do not abuse the @ operator. Although the @ looks simple, there are many actions in the background. 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.
Make good use of strncmp
When you need to contrast the "first n characters" is the same time, with strncmp/strncasecmp, rather than Substr/strtolower, is not PCRE, let alone ereg. STRNCMP/STRNCASECMP efficiency is highest (though not much).
Careful with Substr_compare (PHP5 only)
According to the above truth, Substr_compare should be faster than the first substr more quickly slightly. The answer is in the negative unless:
-Disregard for case comparison
-Relatively large strings

Do not use constants instead of strings
Why:
-Need to query hash table two times
-Need to convert the constant name to lowercase (when the second query is made)
-Generate E_notice Warning
-Creates a temporary string
Efficiency difference: 700%.

Do not put count/strlen/sizeof in a for-loop conditional statement
Tip: My personal approach
QUOTE:
Copy CodeThe code is as follows:
PHP CODE highliting for CU by dZ902
<?php
for ($i = 0, $max = count ($array); $i < $max; + + $i);
?>

Efficiency improvement relative to:
-Count 50%
-Strlen 75%
Short code is not necessarily fast
QUOTE:
Copy CodeThe code is as follows:
PHP CODE highliting for CU by dZ902
<?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 fast?
Efficiency comparison:
-longest:4.27
-longer:4.43
-short:4.76
Incredible? One more:
QUOTE:
Copy CodeThe code is as follows:
PHP CODE highliting for CU by dZ902
<?php
Original
$d = Dir ('. ');
while (($entry = $d->read ())!== false) {
if ($entry = = '. ' $entry = = '. ') {
Continue
}
}
Versus
Glob ('./* ');
Versus (include. and ...)
Scandir ('. ');
?>

Which one is fast?
Efficiency comparison:
-original:3.37
-glob:6.28
-scandir:3.42
-Original without oo:3.14
-SPL (PHP5): 3.95
Narrator: From then on, it can be seen that PHP5 's object-oriented efficiency has been improved a lot, efficiency and pure function is not much worse.
Improve PHP file access efficiency
When you need to include other PHP files, use the full path, or the relative path that is easy to convert.
QUOTE:
Copy CodeThe code is as follows:
PHP CODE highliting for CU by dZ902
<?php
Include ' file.php '; Bad approach
Incldue './file.php '; Good
Include '/path/to/file.php '; Ideal
?>

Maximize
PHP has a lot of extensions and functions available, before implementing a feature, should see if PHP has this functionality? Is there a simpler implementation?
QUOTE:
Copy CodeThe 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 ');
?>

Tips on quoting
References can:
-simplifies access to complex structure data
-Optimize Memory usage

QUOTE:
Copy CodeThe code is as follows:
PHP CODE highliting for CU by dZ902
<?php
$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:
Copy CodeThe code is as follows:
PHP CODE highliting for CU by dZ902
<?php
$a = ' large string ';
Memory Intensive approach
function A ($STR)
{
return $str. ' Something ';
}
More efficient solution
Function A (& $STR)
{
$str. = ' something ';
}
?>


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.