PHP execution speed optimization tips _ PHP Tutorial

Source: Internet
Author: User
Tags glob
Summary of PHP execution speed optimization tips. 1. when file_get_contents can be used to replace file, fopen, feof, fgets, and other methods, try to use file_get_contents, because its efficiency is much higher! Note that file_get_con 1. when file_get_contents can be used to replace file, fopen, feof, fgets, and other methods, use file_get_contents as much as possible because of its high efficiency! Note the PHP version of file_get_contents when opening a URL file;

2. perform as few file operations as possible, although PHP file operations are not efficient;

3. optimize select SQL statements and perform INSERT and UPDATE operations as little as possible (I have been maliciously approved in UPDATE );

4. try to use PHP internal functions as much as possible (but in order to find a function that does not exist in PHP, it is a waste of time to write a user-defined function, experience problems !);

5. do not declare variables inside the loop, especially big variables: objects (doesn't it seem to be a concern in PHP ?);


6. do not use nested values for multi-dimensional arrays;



7. do not use regular expressions when you can use PHP internal strings to operate functions;



8. foreach is more efficient. use foreach instead of the while and for loops;



9. use single quotes instead of double quotes to reference strings;



10. replace I = I + 1 with I + = 1. In line with the c/c ++ habits, the efficiency is high;



11. unset () should be used up for global variables;


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

Tips: PHP5 introduces the concept of static members, which serves as the internal static variables of PHP4 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. 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.

Class foo {
Function bar (){
Echo 'foobar ';
}
}
$ Foo = new foo;
// Instance way
$ Foo-> bar ();
// Static way
Foo: bar ();
?>

Use a class constant (PHP5 ONLY)

Tips: new function of PHP5, similar to const of C ++.

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



(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.



Do not call meaningless functions

Do not use functions when there are corresponding constants.

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%.



The fastest Win32 check

$ Is_win = DIRECTORY_SEPARATOR = '\\';
?>
-No function is required.

-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

(? :)

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 ()



Accelerate strtr

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

$ 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 (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%.



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:


-Case-insensitive comparison

-Relatively large string





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%.





Do not place count/strlen/sizeof in the condition statement of the for loop.

Tips: my personal practices

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

-Count 50%

-Strlen 75%:



Short code is not necessarily fast


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


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



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.

Include 'File. php'; // bad approach
Incldue './file. php'; // good
Include '/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?

$ Filename = "./somepic.gif ";
$ Handle = fopen ($ filename, "rb ");
$ Contents = fread ($ handle, filesize ($ filename ));
Fclose ($ handle );
// Vs. much simpler
File_get_contents ('./somepic.gif ');
?>





References

Reference can be:

-Simplified access to complex structure data

-Optimized 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 ';
}
?>


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

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

The speech collection at the PHP conference is not very rich yet, but the content is a good stuff that makes it easy to get rid of food at a glance. we recommend that you study it carefully when you are sleepy in the morning or after lunch, otherwise, you will forget to eat and go to bed!

Success! But pay attention to file_get_con...

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.