深入for,while,foreach遍历时间比较的详解
程序员文章站
2023-04-07 16:19:07
这个是从别人空间里看来的,不过自己还真从来没这么做过他们三者之间的比较,今天也学习了一下。复制代码 代码如下:
这个是从别人空间里看来的,不过自己还真从来没这么做过他们三者之间的比较,今天也学习了一下。
<?php
$arr = array();
for($i = 0; $i < 50000; $i++){
$arr[] = $i*rand(1000,9999);
}
function getruntime()
{
list($usec,$sec)=explode(" ",microtime());
return ((float)$usec+(float)$sec);
}
/*=============================================*/
$time_start = getruntime();
for($i = 0; $i < count($arr); $i++){
$str = $arr[$i];
}
$time_end = getruntime();
$time_used = $time_end - $time_start;
echo 'used time of for:'.round($time_used, 7).'(s)<br /><br />';
unset($str, $time_start, $time_end, $time_used);
/*=============================================*/
$time_start = getruntime();
while(list($key, $val) = each($arr)){
$str = $val;
}
$time_end = getruntime();
$time_used = $time_end - $time_start;
echo 'used time of while:'.round($time_used, 7).'(s)<br /><br />';
unset($str, $key, $val, $time_start, $time_end, $time_used);
/*=============================================*/
$time_start = getruntime();
foreach($arr as $key => $val){
$str = $val;
}
$time_end = getruntime();
$time_used = $time_end - $time_start;
echo 'used time of foreach:'.round($time_used, 7).'(s)<br /><br />';
?>
复制代码 代码如下:
<?php
$arr = array();
for($i = 0; $i < 50000; $i++){
$arr[] = $i*rand(1000,9999);
}
function getruntime()
{
list($usec,$sec)=explode(" ",microtime());
return ((float)$usec+(float)$sec);
}
/*=============================================*/
$time_start = getruntime();
for($i = 0; $i < count($arr); $i++){
$str = $arr[$i];
}
$time_end = getruntime();
$time_used = $time_end - $time_start;
echo 'used time of for:'.round($time_used, 7).'(s)<br /><br />';
unset($str, $time_start, $time_end, $time_used);
/*=============================================*/
$time_start = getruntime();
while(list($key, $val) = each($arr)){
$str = $val;
}
$time_end = getruntime();
$time_used = $time_end - $time_start;
echo 'used time of while:'.round($time_used, 7).'(s)<br /><br />';
unset($str, $key, $val, $time_start, $time_end, $time_used);
/*=============================================*/
$time_start = getruntime();
foreach($arr as $key => $val){
$str = $val;
}
$time_end = getruntime();
$time_used = $time_end - $time_start;
echo 'used time of foreach:'.round($time_used, 7).'(s)<br /><br />';
?>
上一篇: mysql建立外键
下一篇: 我有个学画画的儿子,败家儿子