php 数组遍历性能的比较
for循环只对数字索引有限;for和foreach遍历结束后不需要对数据进行reset()操作即可供下次遍历,而each方法则需要
//a
$arr=array('a'=>'abc','b'=>123,'c'=>true);
//b
//$arr=range('a','d');//1
for($i=0;$iecho $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是通用的循环结构

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 English version
Recommended: Win version, supports code prompts!

WebStorm Mac version
Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Zend Studio 13.0.1
Powerful PHP integrated development environment