Comparison of php array traversal Performance

Source: Internet
Author: User

The for loop only has limited number indexes. After the for and foreach traversal ends, you do not need to reset () The data for next traversal, while the each method requires

<? Php tutorial
//
$ Arr = array ('A' => 'abc', 'B' => 123, 'c' => true );
// B
// $ Arr = range ('A', 'D ');

// 1
For ($ I = 0; $ I <sizeof ($ arr); $ I ++)
Echo $ arr [$ I]. ',';
Echo '<br/> ';

// 2
Foreach ($ arr as $ key)
Echo "$ key ,";
Echo '<br/> ';

// 3
Foreach ($ arr as $ key => $ val)
Echo "$ key-$ val ,";
Echo '<br/> ';

// 4
Reset ($ arr );
While ($ item = each ($ arr )){
Echo $ item ['key']. '-'. $ item ['value']. ',';
}
Echo '<br/> ';

// 5
Reset ($ arr );
While (list ($ key, $ val) = each ($ arr )){
Echo "$ key-$ val ,";
}
Echo '<br/> ';
?> Use the Statement a $ arr = array ('A' => 'abc', 'B' => 123, 'c' => true ); initialize $ arr to obtain the numeric index array. The output is as follows:

,,,
Abc, 123, 1,
A-abc, b-123, C-1,
A-abc, b-123, C-1,
A-abc, b-123, C-1, use the statement B $ arr = range ('A', 'D'); initialize $ arr to get the associated array, the output is as follows:

A, B, c, d,
A, B, c, d,
0-a, 1-b, 2-c, 3-d,
0-a, 1-b, 2-c, 3-d,
0-a, 1-b, 2-c, 3-d,

After repeated tests, the results show that for traversing the same array, foreach is the fastest, while is the slowest. Foreach is about 20% ~ Faster than while ~ About 30%. Then add the array subscript to 500000 and 5000000. However, in principle, foreach operates on the array copy (by copying the array), while moves the internal indicator of the array. In general logic, while should be faster than foreach (because foreach first copies the array when starting execution, while directly moves the internal indicator .), But the result is just the opposite. The reason should be that foreach is implemented internally in PHP, while is a general loop structure.

 


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.