PHP high performance writing

  • 2020-03-31 21:24:27
  • OfStack

NET to do PHP from 4 years, recently began to pursue high performance ~ ~
So I thought it was time to start a blog
To find things first ~
 
$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 above code
The output is
Us.
Us.
However, the first paragraph is always more complicated than the second paragraph, and the structure is not as clear as the second paragraph.
So why does the first paragraph run so much faster than the second
We can see that in the first piece of code, there are only three ifs,
So how many are going to be in the second paragraph.
We took the switch apart and we were able to look at its basic implementation.
If switch, break is used in every segment of case; In closing,
In fact, the switch is like multiple if{}else if{}

So from this mechanism, we can take
 
foreach( $arr as $key => $value ) 
{ 
switch( $key ) 
{ 
case 'attr1': 
break; 
case 'attr2': 
break; 
case 'attr3': 
break; 
} 
} 

Converted to
 
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 keeps making 1+2+3 decisions based on the number of keys in the array, so it becomes the first piece of code making 3 decisions and the second piece of code making 6 decisions


So you end up with a performance difference of almost twice as fast.

Related articles: