php 数组遍历性能的比较_PHP教程

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

for循环只对数字索引有限;for和foreach遍历结束后不需要对数据进行reset()操作即可供下次遍历,而each方法则需要

//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 '
';
?>使用语句a $arr=array('a'=>'abc','b'=>123,'c'=>true); 对$arr进行初始化得到数字索引数组,输出如下:

, , ,
abc, 123, 1,
a-abc, b-123, c-1,
a-abc, b-123, c-1,
a-abc, b-123, c-1, 使用语句b $arr=range('a','d'); 对$arr进行初始化得到关联数组,输出如下:

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,

经过反复多次测试,结果表明,对于遍历同样一个数组,foreach速度最快,最慢的则是while。foreach比while大约快20% ~ 30%左右。随后再把数组下标增加到500000、5000000测试结果也一样。但从原理上来看,foreach是对数组副本进行操作(通过拷贝数组),而while则通过移动数组内部指标进行操作,一般逻辑下认为,while应该比foreach快(因为foreach在开始执行的时候首先把数组复制进去,而while直接移动内部指标。),但结果刚刚相反。原因应该是,foreach是PHP内部实现,而while是通用的循环结构


www.bkjia.com true http://www.bkjia.com/PHPjc/444745.html TechArticle for循环只对数字索引有限;for和foreach遍历结束后不需要对数据进行reset()操作即可供下次遍历,而each方法则需要 ?php教程 //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
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!