An example of how PHP programming improves program running efficiency. From this point, we can see that the second part of the code will constantly judge the number of keys in the array based on the number of keys, so the number of the first part of the code is 3, second, we can see from this that the second code will constantly judge the number of times of 1 2 3 based on the number of keys in the array, therefore, the first code Judge 3 times, and the second code judge 6 times.
I 've been switching from. NET to PHP4 for years and recently started to pursue high performance ~~
So I thought it was time to write a blog ~
Come to discover things first ~
$ Arr = array (
Attr1 => 1,
Attr2 => 1,
Attr3 => 1,
);
$ StartTime = microtime (true );
For ($ I = 0; I I <1000; $ I)
{
If (isset ($ arr [attr1])
{
}
If (isset ($ arr [attr2])
{
}
If (isset ($ arr [attr3])
{
}
}
$ EndTime = microtime (true );
Printf ("% d us.", ($ endTime-$ startTime) * 1000000 );
$ StartTime = microtime (true );
For ($ I = 0; I 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.", ($ endTime-$ startTime) * 1000000 );
?>
The above code
The output result is
Us.
Us.
However, the first section is more complex than the second section, and the structure is not clear in the second section,
So why is the first segment much faster than the second segment?
We can see that the first code contains only three if,
So how many will there be in the second segment.
Let's take a look at the basic implementation principle of switch.
If break is used in each case in the switch,
In fact, this switch is like multiple if {} else if {}
So from this mechanism, we can
Foreach ($ arr as $ key => $ value)
{
Switch ($ key)
{
Case attr1:
Break;
Case attr2:
Break;
Case attr3:
Break;
}
}
?>
Convert
Foreach ($ arr as $ key => $ value)
{
If ($ key = attr1)
{
}
Else if ($ key = attr2)
{
}
Else if ($ key = attr3)
{
}
}
?>
To understand this, we can see that the second part of the code will constantly judge the number of keys in the array based on the number of keys, therefore, the first code Judge 3 times, and the second code judge 6 times.
Therefore, the number of first code judgments is 3, and the second...