Comparison of php array traversal performance_PHP tutorial

WBOY
Release: 2016-07-20 11:10:19
Original
964 people have browsed it

The for loop only has limited numeric indexes; for and foreach do not need to reset() the data after the traversal is completed to make it available for the next traversal, while the each method requires

//a
$arr=array('a'=>'abc','b'=>123,'c'=>true);
//b
//$arr=range('a','d');

//1 
for($i=0;$i echo $arr[$i].', ';
echo '
';

//2
foreach($arr as $key)
echo "$key, ";
echo '
';

//3
foreach($arr as $key=>$val)
echo " $key-$val, ";
echo '
';

//4
reset($arr);
while($item=each($ arr)){
echo $item['key'].'-'.$item['value'].', ';
}
echo '
';

//5
reset($arr);
while(list($key,$val)=each($arr)){
echo "$key-$val, " ;
}
echo '
';
?>Use the statement a $arr=array('a'=>'abc','b'=>123, 'c'=>true); Initialize $arr to get 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 associative 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, and the slowest is while. foreach is about 20% ~ 30% faster than while. Then increase the array subscript to 500000 and 5000000, and the test results are the same. But from a principle point of view, foreach operates on a copy of the array (by copying the array), while while operates by moving the internal index of the array. Generally speaking, it is believed that while should be faster than foreach (because foreach first places the The array is copied in, while while moves the internal pointer directly), but the result is just the opposite. The reason should be that foreach is an internal implementation of PHP, while while is a general loop structure


www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/444745.htmlTechArticleThe for loop only has limited numeric indexes; there is no need to reset() the data after the for and foreach traversal. Available for next traversal, and each method requires?php tutorial//a $arr=array('a'='a...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!