Tutorial _php Optimizing Build justice and optimizing code in PHP

Source: Internet
Author: User
Tags flock fread switch case
This article summarizes the optimized build justice and optimization code in PHP, and gives PHP programmers a good build justice

1, if the method of the class can be defined as static, as far as possible to define as static, it will increase the speed of nearly 4 times times.

2. The speed of $row [' ID '] is 7 times times that of $row[id].

3. Echo is faster than print, and uses Echo's multiple parameters (referring to commas instead of periods) instead of string connections, such as Echo $str 1, $str 2.

4. To determine the maximum number of cycles before executing a for loop, do not calculate the maximum value once per cycle, preferably using foreach instead.

5. Unregister those unused variables, especially large arrays, in order to free up memory.

6, try to avoid the use of __get,__set,__autoload.

7, require_once () expensive.

8, include files as far as possible to use absolute path, because it avoids PHP to include_path to find the speed of the file, parsing the operating system path takes less time.

9. If you want to know when the script starts executing (that is, the server side receives the client request), use $_server[' request_time '] better than time ().

10, function instead of regular expression to complete the same function.

11, the Str_replace function is faster than the Preg_replace function, but the efficiency of the STRTR function is four times times the Str_replace function.

12, if a string substitution function, can accept an array or character as a parameter, and the parameter length is not too long, then you can consider an extra piece of replacement code, so that each pass argument is a character, rather than write a line of code to accept the array as the query and replace parameters.

13. Use the Select Branch statement (that is, switch case) better than using multiple if,else if statements.

14. Masking error messages with @ is extremely inefficient and extremely inefficient.

15, open the Apache mod_deflate module, can improve the browsing speed of the page.

16, the database connection should be turned off when used, do not use long connection.

17. Error messages are costly.

18, increment the local variable in the method, the speed is the quickest. is almost equivalent to the speed at which local variables are called in the function.

19, incrementing a global variable is twice times slower than incrementing a local variable.

20, incrementing an object property (such as: $this->prop++) is 3 times times slower than incrementing a local variable.

21. Incrementing an undefined local variable is 9 to 10 times times slower than incrementing a pre-defined local variable.

22. Defining only a local variable without calling it in the function also slows down the speed (which is equivalent to incrementing a local variable). PHP will probably check to see if there are global variables.

23. The method invocation appears to be independent of the number of methods defined in the class, because I added 10 methods before and after the test method, but there was no performance change.

24. A method in a derived class runs faster than the same method defined in the base class.

25. Call an empty function with one parameter, which takes the same amount of time as performing a local variable increment operation of 7 to 8 times. A similar method call takes a time close to 15 local variable increment operations.

26, Apache parsing a PHP script time is 2 to 10 times times slower than parsing a static HTML page. Use static HTML pages as much as possible and use fewer scripts.

27. Unless the script can be cached, it will be recompiled every time it is called. Introducing a set of PHP caching mechanisms can typically improve performance by 25% to 100% to eliminate compilation overhead.

28, try to do the cache, you can use memcached. The memcached is a high-performance memory object caching system that can be used to accelerate dynamic Web applications and reduce database load. Caching of the OP code is useful so that the script does not have to recompile for each request.

29. When you manipulate a string and need to verify that its length satisfies a certain requirement, you will of course use the strlen () function. This function executes quite quickly because it does not do any calculations and only returns the length of the known string stored in the Zval structure (the built-in data structure of C for storing PHP variables). However, because strlen () is a function, it is somewhat slower, because function calls go through a number of steps, such as lowercase letters (lowercase, PHP does not differentiate between function names), and hash lookups, which follow the called functions. In some cases, you can use the isset () technique to speed up execution of your code.
(Example below)
if (strlen ($foo) < 5) {echo "Foo is too Short" $$}
(compare with the following tips)
if (!isset ($foo {5})) {echo "Foo is too Short" $$}
Calling Isset () happens to be faster than strlen (), because unlike the latter, Isset (), as a language structure, means that its execution does not require function lookups and lowercase letters. In other words, you're actually not spending much overhead in the top-level code that examines the length of the string.

34. When the increment or decrement of the variable $i is executed, $i + + will be slower $i than + +. This difference is unique to PHP and does not apply to other languages, so please do not modify your C or Java code and expect them to become fast and useless. + + $i is faster because it requires only 3 instructions (opcodes), $i + + requires 4 instructions. The post increment actually produces a temporary variable, which is then incremented. The predecessor increment is incremented directly on the original value. This is one of the most optimized processing, as Zend's PHP optimizer did. It is a good idea to keep this optimization in mind, as not all of the instruction optimizer will do the same optimizations, and there are a large number of Internet service providers (ISPs) and servers that do not have the command optimizer installed.

35, not the object-oriented (OOP), object-oriented tends to be very expensive, each method and object calls will consume a lot of memory.

36, not to use the class to implement all the data structure, arrays are also useful.

37, do not subdivide the method too much, think carefully about what you really want to reuse what code?

38, when you need, you can always break down the code into methods.

39, try to use a large number of PHP built-in functions.

40. If there are a lot of time-consuming functions in your code, you might consider implementing them in C extensions.

41. Evaluate the test (profile) of your code. The inspector will tell you what parts of the code are consuming time. The Xdebug debugger contains an inspection program that can show the bottleneck of the code in general.

42, Mod_zip can be used as Apache module, to compress your data instantly, and to reduce the data transfer volume by 80%.

43, in the case can be replaced with file_get_contents file, fopen, feof, Fgets and other series of methods, as far as possible with the file_get_contents, because his efficiency is much higher! But pay attention to the PHP version of file_get_contents when opening a URL file;

44, as far as possible to file operations, although PHP file operation efficiency is not low;

45, optimize the Select SQL statement, as far as possible, as little as possible to Insert, update operation (on the Update, I was a bad batch);

46, as far as possible the use of PHP internal functions (but I have to find a php non-existent function, wasted can write a custom function time, experience problem Ah!) );

47, the loop inside do not declare variables, especially large variables: objects (this does not seem to be the only thing in PHP to pay attention to it?) )

48. Multidimensional arrays try not to loop nested assignments

49. Do not use regular expressions in cases where PHP internal string manipulation functions are available

50, foreach more efficient, try to use foreach instead of while and for loop

51. Use single quotation mark instead of double quotation mark reference string

52, replace i=i+1 with I+=1. In line with C + + habits, high efficiency

53, to the global variable, should be used up on unset () off

Code optimization Instances


In a function, when passing an array
Using return is more efficient than using global
Like what

function Userloginfo ($usertemp) {
$detail =explode ("|", $usertemp);
return $detail;
}
$login =userloginfo ($USERDB);

Than

function Userloginfo ($usertemp) {
Global $detail;
$detail =explode ("|", $usertemp);
}
Userloginfo ($USERDB);

To be efficient

2, (this code is used to get the program directory corresponding URL, recommended)

$urlarray =explode (@#/@#, $HTTP _server_vars[@ #REQUEST_URI @#]);
$urlcount =count ($urlarray); unset ($urlarray [$urlcount-1]);
$ofstarurl =@ #http://@# $HTTP _server_vars[@ #HTTP_HOST @#].implode (@#/@#, $urlarray);

This piece of code is more

$pre _urlarray=explode (@#/@#, $HTTP _server_vars[@ #HTTP_REFERER @#]);
$pre _url=array_pop ($pre _urlarray);

To be efficient

3, when judging in the loop, the numerical judgment uses the identity to be equal to the efficiency
$a =2; $b = 2;
Like what
if ($a = = $b) $c = $a;
Than
if ($a = = = $b) $c = $a;
Efficient

4,mysql use where in less limit when querying
Limit check many records of the first few, fast, but the query the most face will be slow
With in. On query continuity records, very fast, non-continuity records run slightly slower for the first time, but then faster!

5,NT Server data operation stability is less than unix/linux

6, use Ob_start () as far as possible before output; Can speed up output, applicable NT or Nuli/linux, if use Ob_start (@ #ob_gzhandler @#) for Unlix Class Server, output efficiency will be higher

7, judge when try to use if ($a = = his value) negative when try to use if (empty ($a)), because this program runs faster

8, using Unequal! = is equivalent to <> efficiency

9, personal experience to use $a = "11111111111111"; The efficiency and $a =@ #11111111111111 @#; Not quite as much as the book says.

10, the use of canonical SQL statements, will facilitate the parsing of MySQL

11, using

The code is as follows Copy Code

if ($online) {
$online 1= $online;
Setcookie (@ #online1 @#, $online, $cookietime, $ckpath, $ckdomain, $secure);
}

The cookie will take effect immediately.
Use

if ($online)
Setcookie (@ #online1 @#, $online, $cookietime, $ckpath, $ckdomain, $secure);


The cookie needs to be refreshed again to take effect

12, using

The code is as follows Copy Code

$handle =fopen ($filename, WB);
Flock ($handle, lock_sh);
$filedata =fread ($handle, FileSize ($filename));
Fclose ($handle);

Than

File ($filename);

Be good at speed or stability

13, truncated string optimization function (can avoid the appearance of characters)

The code is as follows Copy Code

function Substrs ($content, $length) {
if (strlen ($content) > $length) {
$num = 0;
for ($i =0; $i < $length-3; $i + +) {
if (Ord ($content [$i]) >127) $num + +;
}
$num%2==1? $content =substr ($content, 0, $length-4): $content =substr ($content, 0, $length-3);
$content. =@#. @#;
}
return $content;
}


such as $newarray[1]=substrs ($newarray [1],25);

14, screen case in program

The code is as follows Copy Code
for ($asc =65; $ASC <=90; $ASC + +)
{//strtolower () This function is garbled on some servers!
if (Strrpos ($regname, Chr ($ASC))!==false)
{
$error = "In order to avoid user name confusion, the use of uppercase letters in the user name, please use lowercase letter";
$reg _check=0;
}
}

15, do not use file (), and do not use Fget ();(unstable or slow) to take an array function

copy code
function openfile ($filename, $method = "RB")
{
$handle = @fopen ($filename, $method);
@flock ($handle, lock_sh);
@ $filedata =fread ($handle, FileSize ($filename));
@fclose ($handle);
$filedata =str_replace ("", " ", $filedata);
$filedb =explode (" ", $filedata);
//array_pop ($filedb);
$count =count ($filedb);
if ($filedb [$count -1]==@#) {unset ($filedb [$count-1]);}
return $filedb;
}

This function although the code is more, but in speed and stability advantage is very big!


Implementing an array separation code like above

After that, it is very convenient to access the block data of the Temparray.

The code is as follows Copy Code

foreach ($tempArray as $row) {

array1[$row [' ID ']] = $row [' Key '];

array2[$row [' Key ']][] = $row;

}

Access

and handling code

The code is as follows Copy Code

foreach ($array 1 as $ID = = $Key) {

$this->dosomething ($ID);

Access Temparray block array $array2[$Key]

$this->dosomething2 ($array 2[$Key]);

}

http://www.bkjia.com/PHPjc/629081.html www.bkjia.com true http://www.bkjia.com/PHPjc/629081.html techarticle This article summarizes the optimized build justice and optimization code in PHP, gives PHP programmers a good build justice 1, if you can define the method of the class as static, as far as possible to define static, it will increase the speed ...

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