Generally, there are three methods for traversing 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.
Let us first test the time it takes to traverse a one-dimensional array with 50,000 subscripts:
Test platform:
CPU: PM 725
Memory: 512M
Hard drive: 40G 5400 rpm
OS: Windows XP SP2
WEB: apache 2.0.54 php5.0.4
test code:
<?php
/*
* @ Author: Lilov
* @ Homepage: www.codesky.com
* @ E-mail: [email protected]
*
*/
$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>';
#####################################
?>
Test results:
average the three test results :
Corresponds to for, while, foreach respectively
0.1311650
0.1666853
0.1237440
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.
Therefore, 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.