一般情况下,遍历一个数组有三种方法,for、while、foreach。其中最简单方便的是foreach。那么它们在操作和性能上存在什么差别,通常使用那种方法比较好。
下面先让我们来测试一下共同遍历一个有50000个下标的一维数组所耗的时间:
测试平台:
CPU:P-M 725
内存:512M
硬盘:40G 5400转
OS:Windows XP SP2
WEB:apache 2.0.54 php5.0.4
测试代码:
<?php
/*
* @ Author: Lilov
* @ Homepage: http://www.codesky.com
* @ E-mail: zhongjiechao@gmail.com
*
*/
$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);
######################
下面先让我们来测试一下共同遍历一个有50000个下标的一维数组所耗的时间:
测试平台:
CPU:P-M 725
内存:512M
硬盘:40G 5400转
OS:Windows XP SP2
WEB:apache 2.0.54 php5.0.4
测试代码:
<?php
/*
* @ Author: Lilov
* @ Homepage: http://www.codesky.com
* @ E-mail: zhongjiechao@gmail.com
*
*/
$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);
######################
| 对此文章发表了评论 |
