note 95179 deleted from function.sizeof by danbrown
| From: | danbrown@php.net | Date: | Wed, 16 Dec 2009 23:58:46 +0000 |
| Subject: | note 95179 deleted from function.sizeof by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-164063@lists.php.net to get a copy of this message | ||
Note Submitter: cincodenada at gmail dot com
----
The previous note by Emil Mohamed with the test runs is true only if you don't want to do
anything with the values in the array. If you want to actually use the array values, foreach is
faster. I edited his script as follows, assigning the value of the array element to $res:
<?php
$arr = array();
$num = 1000000;
echo "Populating test array with $num elements ... ";
for($i=0; $i<$num; $i++) {
$arr[$i] = microtime(true) . mt_rand();
}
echo "Populated.\n\n";
echo "Start testing FOREACH ... \n";
$start_time = microtime(true);
foreach ($arr as $i=>$elem) {
$res = $elem;
}
echo "FOREACH result: " . (microtime(true) - $start_time) . "\n\n";
echo "Start testing regular FOR ... \n";
$start_time = microtime(true);
for ($i=0; $i<sizeof($arr); $i++) {
$res = $arr[$i];
}
echo "Regular for result: " . (microtime(true) - $start_time) . "\n\n";
echo "Starting test for pre-computed size array FOR ... \n";
$start_time = microtime(true);
$sizeof_arr = sizeof($arr);
for ($i=0; $i<$sizeof_arr; $i++) {
$res = $arr[$i];
}
echo "pre-computed size of array FOR: " . (microtime(true) - $start_time) .
"\n";
?>
And got this output:
Populating test array with 1000000 elements ... Populated.
Start testing FOREACH ...
FOREACH result: 0.156778097153
Start testing regular FOR ...
Regular for result: 0.336126089096
Starting test for pre-computed size array FOR ...
pre-computed size of array FOR: 0.164707899094
Which stayed consistent for the three runs that I did. It seems that the extra slowness of FOREACH
in Emil's example is from the assignment of $elem, which is not available in either FOR, and
needs to be done within the loop, as my test does. Given this, FOREACH is indeed faster.