Generally, there are three ways to traverse an array, for, while, foreach. One of the simplest and most convenient is foreach. So what are the differences between their operations and their performance, which is usually better to use that method.
Let's start by testing the time it takes to traverse a one-dimensional array with 50,000 subscripts:
Test Platform:
CPU:P-M 725
Memory: 512M
Hard drive: 40G 5400 rpm
Os:windows XP SP2
Web:apache 2.0.54 php5.0.4
Test code:
<?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 the for: '. Round ($time _used, 7). ' (s) <br><br> ';
Unset ($str, $time _start, $time _end, $time _used);
######################################
$time _start = GetRuntime ();
while (the list ($key, $val) = each ($arr)) {
$str. = $val;
}
$time _end = GetRuntime ();
$time _used = $time _end-$time _start;
Echo ' Used time of: '. 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:
Averaging three test results:
Corresponding for, while, foreach
0.1311650
0.1666853
0.1237440
After repeated tests, the results show that foreach is the fastest and slowest while traversing the same array. foreach is about 20% ~ 30% faster than while. Then add the array subscript to 500000, 5000000 test results are the same. But the principle is that foreach is an array copy of operations (by copying arrays), while whilst while moving through an array of internal metrics, it is generally logical that while should be faster than foreach (because foreach first copies the array when it starts executing), While the while directly moving internal indicators. ), but the result is just the opposite. The reason for this is that foreach is the internal implementation of PHP while the while is the universal loop structure.
Therefore, I prefer to use foreach form in the usual application, simple, and high efficiency. Under PHP5, foreach can also traverse the properties of a class.