Generally, there are three methods to traverse an array, for, while, and foreach. The simplest and most convenient of them is foreach. So what are the differences in operation and performance between them? Which method is usually better to use. Test platform: Test code: $arr = array(); function GetRunTime() for($i = 0; $i < count($arr); $i++){ $time_end = GetRunTime(); echo Used time of for:.round($time_used, 7).(s) while(list($key, $val) = each($arr)){ $time_end = GetRunTime(); echo Used time of while:.round($time_used, 7).(s) foreach($arr as $key => $val){ $time_end = GetRunTime(); ?> Test results: Average the three test results: 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. So, in general applications, I prefer to use the foreach form, which is simple and efficient. Under PHP5, foreach can also traverse the attributes of a class.
Let us first test the time it takes to traverse a one-dimensional array with 50,000 subscripts:
CPU: P-M 725
Memory: 512M
Hard disk: 40G 5400 rpm
OS: Windows XP SP2
WEB: apache 2.0.54 php5.0.4
/*
* @ Author: Lilov
* @ Homepage: www.codesky.com
* @ E-mail: zhongjiechao@gmail .com
*
*/
for($i = 0; $i < 50000; $i++){
$arr[] = $i*rand(1000,9999);
}
{
list($usec,$sec)=explode(" ",microtime());
return ((float)$usec+(float)$sec);
}
####################################
$time_start = GetRunTime();
$str .= $arr[$i];
}
$time_used = $time_end - $time_start;
;
unset($str, $time_start, $time_end, $time_used);
####################################
$time_start = GetRunTime();
$str .= $val;
}
$time_used = $time_end - $time_start;
;
unset($str, $key, $val, $time_start, $time_end, $time_used);
#####################################
$time_start = GetRunTime();
$str .= $val;
}
$time_used = $time_end - $time_start;
echo Used time of foreach:.round($time_used, 7).(s)
#####################################
corresponds to for, while, and foreach respectively
0.1311650
0.1666853
0.1237440