Array search performance

5:22 pm PHP

You probably have often searched for a value in an array using the in_array() function. Reading php|architect’s Guide to PHP Security by Ilia Alshanetsky, I’ve noticed that searching on values can be slower than searching on keys. I’ve wanted to compare performance between the three methods to check a value in a white list and it’s amazing how slower is in_array(), look at the result :

fga@brian:~/tmp$ php5 test_array.php
With in_array :
111
time : 0.349022865295 sec
With isset on keys :
111
time : 0.000214099884033 sec
With array_key_exists :
111
time : 0.00021505355835 sec

Searching on keys is 1000 to 10000 times faster regarding the bench on an array containing 700 000 elements.

Here is the code of the test :

<?php
// array to store white list as values
$t = array();
// array to store white list as keys
$u = array();

// elements count
$max = 700000;

$first = $last = $middle = '';
for($i=$max-1;$i>=0;$i--){
        // values are random strings
        $id = uniqid(rand());
        $t[] = $id;
        $u[$id] = '';
        // we store first, last and middle values to
        // to search for them
        switch($i) {
                case $max-1:
                        $first = $id;
                break;
                case 0:
                        $last = $id;
                break;
                case $max/2:
                        $middle = $id;
                break;
        }
}

echo "With in_array :\n";
$start_time = microtime(true);
echo in_array($first,$t);
echo in_array($last,$t);
echo in_array($middle,$t);
echo "\n";
echo "time : " . (microtime(true)-$start_time) . " sec";
echo "\n";

echo "With isset on keys :\n";
$start_time = microtime(true);
echo isset($u[$first]);
echo isset($u[$last]);
echo isset($u[$middle]);
echo "\n";
echo "time : " . (microtime(true)-$start_time) . " sec";
echo "\n";

echo "With array_key_exists :\n";
$start_time = microtime(true);
echo array_key_exists($first,$u);
echo array_key_exists($last,$u);
echo array_key_exists($middle,$u);
echo "\n";
echo "time : " . (microtime(true)-$start_time) . " sec";
echo "\n";
Leave a Comment

Your comment

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.