Home > Backend Development > PHP Tutorial > php high performance writing

php high performance writing

WBOY
Release: 2016-07-29 08:43:59
Original
963 people have browsed it

It has been 4 years since I switched from .NET to PHP, and recently I started to pursue high performance~~
So I started to think it’s time to write a blog~
Let’s discover something first~

Copy the code The code is as follows:


$arr = array(
'attr1' => 1 ,
'attr2' => 1 ,
'attr3' => 1 ,
);
$startTime = microtime( true );
for( $i = 0 ; $i < 1000 ; $i++ )
{
if( isset( $arr['attr1'] ) )
{
}
if( isset( $arr['attr2'] ) )
{
}
if( isset( $arr['attr3'] ) )
{
}
}
$endTime = microtime( true );
printf( "%d us.n" , ( $endTime - $startTime ) * 1000000 ) ;
$startTime = microtime( true );
for( $i = 0 ; $i < 1000 ; $i++ )
{
foreach( $arr as $key => $value )
{
switch( $key )
{
case 'attr1':
break;
case 'attr2':
break;
case 'attr3':
break;
}
}
}
$endTime = microtime( true );
printf( "% d us.n" , ( $endTime - $startTime ) * 1000000 );


The output result of the above code
is
us.
us.
However, no matter how you look at it, the first paragraph is more cumbersome than the second paragraph, and The structure is not as clear as the second paragraph.
So why does the first paragraph execute so much faster than the second paragraph?
We can see that there are only 3 ifs in the first paragraph of code.
How many ifs will there be in the second paragraph? Woolen cloth.
We have disassembled the switch and can take a look at its basic implementation principles.
If each case in the switch ends with break;,
In fact, this switch is like multiple if{}else if{}
So from this mechanism, we can copy the code

The code is as follows:

foreach( $arr as $key => $value )

{
switch( $key )
{
case 'attr1':
break;
case 'attr2':
break;
case ' attr3':
break;
}
}


converted to



Copy code The code is as follows:

foreach( $arr as $key => $value )

{
if( $key = = 'attr1' )
{
}
else if( $key == 'attr2' )
{
}
else if( $key == 'attr3' )
{
}
}


to understand,

As you can see from here, the second piece of code will continuously make judgments of 1+2+3 according to the number of keys in the array, so the number of judgments of the first piece of code is 3, and The number of judgments in the second piece of code is 6 times
, so the execution efficiency is nearly doubled.
The above has introduced PHP high-performance writing, including aspects of it. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template