Very practical php skills

Source: Internet
Author: User
Tags glob

This essay is translated from various documents on the network (see the last reference), especially the speeches delivered by Ilia Alshanetsky at multiple PHP conferences, it mainly involves various techniques to improve PHP performance. For accuracy, many sections have detailed efficiency data and corresponding versions. If you are lazy, the data will not be given one by one and you can draw a conclusion directly. If you need to read the original document, please refer to the "references" section at the end of the article. The orange title is the recommendation part.

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

[Size = + 2] The static call member must be defined as static (PHP5 ONLY)

Tip: PHP 5 introduces the concept of static members, which is used in the same way as the static variables in PHP 4 functions, but the former is used as a member of the class. Static variables are similar to class variable in Ruby. All class instances share the same static variables.

QUOTE:
// 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 ();
?>

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.

[Size = + 2] use a class constant (PHP5 ONLY)

Tip: PHP 5's new features are similar to C ++'s const.

The benefit of using a class constant is:

-No additional overhead for parsing during compilation
-The pooled tables are 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

[Size = + 2] (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 APC cache system has solved this problem.

File I/O increase => efficiency reduction

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

[Size = + 2] Do not call meaningless functions

Do not use functions when there are corresponding constants.

QUOTE:
// 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, the efficiency is improved by about 3500%.

[Size = + 2] The fastest Win32 check

QUOTE:
// Php code Highliting for CU by dZ902

<? Php
$ Is_win = DIRECTORY_SEPARATOR = '//';
?>

-No function is required.
-Win98/NT/2000/XP/Vista/Longhorn/Shorthorn/Whistler... General
-Always available

[Size = + 2] 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.

[Size = + 2] accelerating PCRE

(?

In this way, PHP does not need to allocate memory for the corresponding content, saving the cost. Efficiency is improved by about 15%.

-Regular expressions are not required. Read the "string functions" section of the manual during analysis. Are there any useful functions you missed?

For example:

Strpbrk ()
Strncasecmp ()
Strpos ()/strrpos ()/stripos ()/strripos ()

[Size = + 2] accelerating strtr

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

Quote:
// 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.

[Size = + 2] do not replace unnecessary values

Even if it is not replaced, str_replace allocates memory for its parameters. Very slow! Solution:

-Use strpos to search for it (very fast) and check whether it needs to be replaced. If necessary, replace it.

Efficiency:

-To replace: the efficiency is almost the same, with a difference of about 0.1%.
-If no replacement is required: Use strpos to increase speed by 200%.

[Size = + 2] 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.

[Size = + 2] 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 ).

[Size = + 2] Use substr_compare (PHP5 ONLY) with caution)

As mentioned above, substr_compare should be faster than substr. The answer is no, unless:

-Case-insensitive comparison
-Relatively large string

[Size = + 2] Do not use constants instead of strings

Why:

-You need to query the duplicate table twice.
-You need to convert the constant name to lowercase (when performing the second query)
-Generate an E_NOTICE warning.
-A temporary string is created.

Efficiency difference: 700%.

[Size = + 2] do not place count/strlen/sizeof in the Condition Statement of the for loop.

Tip: My personal practices

QUOTE:
// Php code Highliting for CU by dZ902

<? Php
For ($ I = 0, $ max = count ($ array); $ I <$ max; ++ $ I );
?>

Efficiency improvement:

-Count 50%
-Strlen 75%:

[Size = + 2] short code is not necessarily fast

Quote:
// PHP code highliting for Cu by dz902

<? PHP
// Longest
If ($ A = $ B ){
$ Str. = $;
} Else {
$ Str. = $ B;
}

// Longer
If ($ A = $ B ){
$ Str. = $;
}
$ 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? Next:

Quote:
// PHP code highliting for Cu by dz902

<? PHP
// Original
$ D = dir ('.');
While ($ entry = $ d-> read ())! = False ){
If ($ entry = '.' | $ entry = '..'){
Continue;
}
}

//
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, we can see that PHP5's object-oriented efficiency has improved a lot, and the efficiency is not much worse than pure functions.

[Size = + 2] Improving 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.

QUOTE:
// Php code Highliting for CU by dZ902

<? Php

Include 'file. php'; // bad approach

Incldue './file. php'; // good

Include '/path/to/file. php'; // ideal

?>

[Size = + 2] make the best use of everything

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

QUOTE:
// 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 ');
?>

[Size = + 2] References

Reference can be:

-Simplified access to complex structure data
-Optimized memory usage

QUOTE:
// 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:
// 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 ';
}
?>

========================================================== ======
[Size = + 2] References

Http://ilia.ws

Ilia's personal website, Blog, links to the development and publishing of some articles, etc.

Http://ez.no

On the official website of eZ components, eZ comp is an open-source general library for PHP5. It takes efficiency as its mission and Ilia is also involved in development.

Http://phparch.com

Php | effecect, a good php Publisher/training organization. If you can't afford it or can't buy it, you can go online to many classic pirated versions.

Http://talks.php.net

This article from the CSDN blog, reproduced please indicate the source: http://blog.csdn.net/phphot/archive/2007/08/08/1731403.aspx

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.