Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save alcaeus/536156663fac96744eba77b3e133e50a to your computer and use it in GitHub Desktop.
Save alcaeus/536156663fac96744eba77b3e133e50a to your computer and use it in GitHub Desktop.
Performance comparision: in-array vs. isset vs. array_key_exists
<?php declare(strict_types = 1);
function testPerformance($name, Closure $closure, $runs = 1000000)
{
$start = microtime(true);
for (; $runs > 0; $runs--)
{
$closure();
}
$end = microtime(true);
printf("Function call %s took %.5f seconds\n", $name, $end - $start);
}
$items = [1111111];
for ($i = 0; $i < 100000; $i++) {
$items[] = rand(0, 1000000);
}
$items = array_unique($items);
shuffle($items);
$assocItems = array_combine($items, array_fill(0, count($items), true));
$in_array = function () use ($items) {
in_array(1111111, $items);
};
$isset = function () use ($assocItems) {
isset($items[1111111]);
};
$array_key_exists = function () use ($assocItems) {
array_key_exists(1111111, $assocItems);
};
testPerformance('in_array', $in_array, 100000);
testPerformance('isset', $isset, 100000);
testPerformance('array_key_exists', $array_key_exists, 100000);
$ php in_array_vs_isset_vs_array_key_exists.php 
Function call in_array took 1.51871 seconds
Function call isset took 0.14684 seconds
Function call array_key_exists took 0.22123 seconds
@klc
Copy link

klc commented Jul 3, 2024

PHP Version 8.3.7 (cli)
MacOS 14.5
Apple M1 Pro 16GB

Run #1

Function call in_array took 4.55296 seconds
Function call isset took 0.00325 seconds
Function call array_key_exists took 0.00316 seconds

Run #2

Function call in_array took 2.22286 seconds
Function call isset took 0.00329 seconds
Function call array_key_exists took 0.00327 seconds

Run #3


Function call in_array took 2.20876 seconds
Function call isset took 0.00315 seconds
Function call array_key_exists took 0.00303 seconds

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment