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

*/

?>

Comments (0)

› No comments yet.

Leave a Reply

Allowed Tags - You may use these HTML tags and attributes in your comment.

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Pingbacks (0)

› No pingbacks yet.