Optimization with in_array()

Ever wonder with many in_array() checks, you can speed it up depending on your scenario. In my case, 99% it’s empty so it’s better with an empty() check

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

$vStart = microtime(true);
for ($i=1;$i<$vLimit; $i++) {
if (in_array(123,$vAry)) {
}
} // rof
$vResult[] = “NoEmptyCheck= “.(microtime(true)-$vStart);

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

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

/* Result

For an often-non-empty array scenario:
– NoEmptyCheck= 3.76290512085
– WithEmptyCheck= 4.59545087814

For an often-empty array scenario:
– NoEmptyCheck= 3.46415710449
– WithEmptyCheck= 1.08467411995

*/

?>


Posted

in

by

Tags:

Comments

Leave a Reply

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