note 40415 deleted from control-structures.while by nlopess
| From: | nlopess@php.net | Date: | Wed, 03 Mar 2004 17:47:00 +0000 |
| Subject: | note 40415 deleted from control-structures.while by nlopess | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-66201@lists.php.net to get a copy of this message | ||
Note Submitter: greg@serberus.co.uk
----
Benchmarking while()'s and for()'s shows that including the count() function inside the
loop doesn't result in a performance penalty, just the reverse! (weird eh)
Please note I was using a PHP3 install to test this, hence the use of registered globals. $_SERVER
should be used where available (most PHP4 installs).
<?php
function getmicrotime()
{
list($usec, $sec) = explode(' ', microtime());
return ((float)$usec + (float)$sec);
}
$hsv = $HTTP_SERVER_VARS;
// get HTTP_SERVER_VARS keys
while (list($key,) = each($hsv))
$arrUnset[] = $key;
/************************************
* dummy run, discard result presumably
* not cached like subsequent runs
*************************************/
for ($x=0; $x < count($hsv); $x++)
if (isset($hsv[$arrUnset[$x]])) unset($hsv[$arrUnset[$x]]);
/************************************
* inefficient, leaves count in the loop
*************************************/
$hsv = $HTTP_SERVER_VARS;
$start = getmicrotime();
for ($x=0; $x < count($hsv); $x++)
if (isset($hsv[$arrUnset[$x]])) unset($hsv[$arrUnset[$x]]);
$end = getmicrotime();
$time = $end - $start;
echo $time.' secs<br>';
/************************************
* theoretically faster, count outside loop
************************************/
$hsv = $HTTP_SERVER_VARS;
$start = getmicrotime();
$xMax = count($hsv);
for ($x=0; $x < $xMax; $x++)
if (isset($hsv[$arrUnset[$x]])) unset($hsv[$arrUnset[$x]]);
$end = getmicrotime();
$time = $end - $start;
echo $time.' secs<br>';
/************************************
* fastest surely?
************************************/
$hsv = $HTTP_SERVER_VARS;
$start = getmicrotime();
$x = 0;
$xMax = count($hsv);
while ($x < $xMax) {
if (isset($hsv[$arrUnset[$x]])) unset($hsv[$arrUnset[$x]]);
$x++;
}
$end = getmicrotime();
$time = $end - $start;
echo $time.' secs<br>';
/************************************
* count() in while(), yet seems to be
* the fastest?!?
************************************/
$hsv = $HTTP_SERVER_VARS;
$start = getmicrotime();
$x = 0;
while ($x < count($hsv)) {
if (isset($hsv[$arrUnset[$x]])) unset($hsv[$arrUnset[$x]]);
$x++;
}
$end = getmicrotime();
$time = $end - $start;
echo $time.' secs<br>';
?>
Typical results I got:
0.00027918815612793 secs
0.00036120414733887 secs
0.00038599967956543 secs
0.00023579597473145 secs
All previous teachings have said to move count()'s outside of loops, one of most basic
performance optimisations but it doesn't seem to apply here...
Does this suggest the result of count() is cached?