From. NET to do PHP4 years, and recently began to pursue high performance ~ ~
So I started to think it was time to write a blog.
Come and find something first ~
Copy CodeThe code is as follows:
$arr = Array (
' Attr1 ' = 1,
' Attr2 ' = 1,
' Attr3 ' = 1,
);
$startTime = Microtime (true);
for ($i = 0; $i <; $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 <; $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 section of code
The output is
us.
us.
However, it is the first paragraph more cumbersome than the second paragraph, and the structure is not the second paragraph clear,
So why does the first paragraph run so much faster than the second?
We can see that the first paragraph of the code, only 3 if,
So how many are there in the second paragraph?
We opened the switch and we could see his basic principle of implementation.
If the switch has a break in each case, the end
In fact, this switch is like multiple If{}else if{}
So from this mechanism, we can put the
Copy CodeThe code is as follows:
foreach ($arr as $key = $value)
{
Switch ($key)
{
Case ' ATTR1 ':
Break
Case ' ATTR2 ':
Break
Case ' ATTR3 ':
Break
}
}
Converted Into
Copy CodeThe code is as follows:
foreach ($arr as $key = $value)
{
if ($key = = ' attr1 ')
{
}
else if ($key = = ' attr2 ')
{
}
else if ($key = = ' Attr3 ')
{
}
}
To understand,
From here, we can see that the second code will be determined by the number of keys in the array to judge the number of times to 1+2+3, so it becomes the first code to determine the number of times is 3, and the second code to determine the number of times is 6
As a result, the efficiency of execution is nearly one-fold faster.
http://www.bkjia.com/PHPjc/322581.html www.bkjia.com true http://www.bkjia.com/PHPjc/322581.html techarticle from. NET to do PHP4 years, and recently began to pursue high-performance ~ ~ So began to think it is time to write blog ~ to find something first ~ Copy the code code as follows: $arr = Array (' at ...