Php high-performance writing

Source: Internet
Author: User

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 ~
Copy codeThe Code is as follows:
$ 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. \ n", ($ 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. \ n", ($ 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
Copy codeThe Code is as follows:
Foreach ($ arr as $ key => $ value)
{
Switch ($ key)
{
Case 'attr1 ':
Break;
Case 'attr2 ':
Break;
Case 'attr3 ':
Break;
}
}

Convert
Copy codeThe Code is as follows:
Foreach ($ arr as $ key => $ value)
{
If ($ key = 'attr1 ')
{

}
Else if ($ key = 'attr2 ')
{

}
Else if ($ key = 'attr3 ')
{

}
}


Understanding,
From this we can see that the second code will constantly judge the number of keys in the array for 1 + 2 + 3 times, therefore, the first code Judge 3 times, and the second code judge 6 times.


Therefore, the execution efficiency is almost doubled.

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.