Squeeze details of PHP Performance

Source: Internet
Author: User

PHP can improve the execution efficiency from many details. The following is a summary.

Static call Members must be defined as static (PHP5 ONLY)

PHP 5 introduces the concept of static members, which is used as a member of the class, and is consistent with the static variables in the function of PHP 4. Static variables are similar to class variable in Ruby. All class instances share the same static variables.

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

Static calling uses non-static members, which is 50-60% slower than static calling. This is mainly because the former generates an E_STRICT warning and the internal switch is also required.

Use a class constant (PHP5 ONLY)

The new function of PHP 5 is similar to the const of C ++.

The benefit of using a class constant is:

  • No additional overhead for parsing during compilation
  • The table is smaller, so internal search is faster.
  • The class constant only exists in the specified namespace, so the name of the miscellaneous is shorter.
  • Code cleaner to make debugging easier
(Temporarily) do not use require/include_once

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

If the absolute path is used, PHP 5.2/6.0 does not have this problem. The new version of APC cache system has solved this problem.

File I/O increase => efficiency is reduced. If necessary, you can check whether the file has been require/include.

Do not call meaningless functions

Do not use functions when there are corresponding constants.

<?phpphp_uname('s') == PHP_OS;php_version() == PHP_VERSION;php_sapi_name() == PHP_SAPI;?>

Although not used much, the efficiency is improved by about 3500%.

The fastest Win32 check
<?php$is_win = DIRECTORY_SEPARATOR == '\\';?>
  • No Function
  • Win98/NT/2000/XP/Vista/Longhorn/Shorthorn/Whistler... General
  • Always available
Time Problem (PHP> 5.1.0 ONLY)

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

However, it is always slow to call a function.

Now, we can use $ _ SERVER ['request _ time'] To save the trouble of calling a function.

PCRE Acceleration

For results that do not need to be saved, do not use (), all use (? :). In this way, PHP does not need to allocate memory for the corresponding content, saving the cost. Efficiency is improved by about 15%.

If you do not need regular expressions, you do not need regular expressions. Read the "string functions" section of the manual carefully during analysis. Are there any useful functions you missed?

Accelerate strtr

If all the characters to be converted are single characters, use strings instead of arrays for strtr:

<?php$addr = strtr($addr, "abcd", "efgh"); // good$addr = strtr($addr, array('a' => 'e',                        // ...                        )); // bad?>

Efficiency Improvement: 10 times.

Do not make unnecessary replacement

Even if it is not replaced, str_replace allocates memory for its parameters. Very slow! Solution: Use strpos to search for it first (very fast) and check whether it needs to be replaced. If necessary, replace it.

If you need to replace: the efficiency is almost the same, and the difference is about 0.1%. If you do not need to replace: Use strpos to speed up to 200%.

Evil @ Operator

Do not abuse the @ operator. Although @ looks simple, there are actually many operations in the background. Compared with @, the efficiency difference is 3 times.

In particular, do not use @ in a loop. In five loop tests, even if the error is disabled with error_reporting (0), enabling it after the loop is completed is faster than using.

Use strncmp

Use strncmp/strncasecmp instead of substr/strtolower to compare the first n characters, not to mention ereg. Strncmp/strncasecmp is the most efficient (although not high ).

Use substr_compare (PHP5 ONLY) with caution)

As mentioned above, substr_compare should be faster than substr. The answer is no, unless the case-insensitive comparison is ignored and a large string is used.

Do not use constants instead of strings.


  • You need to query the duplicate table twice.
  • The constant name needs to be converted to lowercase (when the second query is performed)
  • Generate E_NOTICE warning
  • Creates a temporary string.

Efficiency difference: 700%.

Do not place count/strlen/sizeof in the Condition Statement of the for loop.

My personal practices

<?phpfor ($i = 0, $max = count($array);$i < $max; ++$i);?>
Short code is not necessarily fast

Which one do you think is faster?

- longest: 4.27- longer: 4.43- short: 4.76

Incredible? Next:

<?php// original$d = dir('.');while (($entry = $d->read()) !== false) {if ($entry == '.' || $entry == '..') {       continue;}}// versusglob('./*');// versus (include . and ..)scandir('.');?>

Efficiency Comparison:

- original: 3.37- glob: 6.28- scandir: 3.42- original without OO: 3.14- SPL (PHP5): 3.95

From then on, we can see that the object-oriented efficiency of PHP5 has improved a lot, and the efficiency is not much worse than that of pure functions.

Improve PHP file access efficiency

When other PHP files need to be included, use the full path or the relative path that is easy to convert.

<?phpinclude 'file.php'; // bad approachincldue './file.php'; // goodinclude '/path/to/file.php'; // ideal?>
Best use

PHP has many extensions and functions available. Before implementing a function, check whether PHP has this function? Is there a simpler implementation?

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

References can simplify access to complex structured data and optimize memory usage.

<?php$a['b']['c'] = array();// slow 2 extra hash lookups per accessfor ($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;?>
<?php$a = 'large string';// memory intensive approachfunction a($str){return $str.'something';}// more efficient solutionfunction 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.