Improve Performance of in_array()

When the array size is large, performance of the built-in function in_array() will be extremely poor. To solve this problem, we can implement a custom in_array() function using hash maps. Here is the source code:

$map = array();
foreach($a as $val) {
  $map[$val] = 1;
}
function better_in_array($needle, $map) {
  return isset($map[$needle]);
}

Let’s compare the performance now:

$a = array();
for ($i=0; $i<100000; $i++) {
  $a[$i] = uniqid(rand()); 
}
function better_in_array($needle, $map) { 
  return isset($map[$neddle]); 
} 

$ts = microtime(true); 
for ($i=0; $i<1000; $i++) {
  in_array($i, $a); 
}
printf("in_array=%.4f\n", microtime(true) - $ts); 

$ts = microtime(true); 
$map = array(); 
foreach($a as $val) {
  $map[$val] = 1; 
}
for ($i=0; $i<1000; $i++) {
  better_in_array($i, $map); 
}
printf("better_in_array=%.4f\n", microtime(true) - $ts);

Result:

in_array=17.8276
better_in_array=0.0706

Leave a Reply

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