Optimization with foreach() an empty array

<?php
$vResult = array();
$vAry = array(‘abc’);
$vLimit = 10000000;

$vStart = microtime(true);
for ($i=1;$i<$vLimit; $i++) {
foreach ($vAry as $a) {}
} // rof
$vResult[] = “NoEmptyCheck= “.(microtime(true)-$vStart);

$vStart = microtime(true);
for ($i=1;$i<$vLimit; $i++) {
if (!empty($vAry)) {
foreach ($vAry as $a) {}
}
} // rof
$vResult[] = “WithEmptyCheck= “.(microtime(true)-$vStart);

echo implode(“\n”,$vResult).”\n”;

/* Result

For an often-non-empty array scenario:
NoEmptyCheck= 2.10900402069
WithEmptyCheck= 2.59749412537

For an often-empty array scenario:
– NoEmptyCheck= 1.08695101738
– WithEmptyCheck= 1.01621007919

*/

?>


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *