Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save sanmai/d866617fed5e4aa1e3eee15c78abf39a to your computer and use it in GitHub Desktop.
Save sanmai/d866617fed5e4aa1e3eee15c78abf39a to your computer and use it in GitHub Desktop.
Performance comparision: isset vs. array_key_exists
<?php
function testPerformance($name, Closure $closure, $runs)
{
$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));
$isset = function () use ($assocItems) {
return isset($items[1111111]);
};
$array_key_exists = function () use ($assocItems) {
return array_key_exists(1111111, $assocItems);
};
testPerformance('isset', $isset, 10000000);
testPerformance('array_key_exists', $array_key_exists, 10000000);
$ php -n --version
PHP 7.3.15-3 (cli) (built: Feb 23 2020 07:15:44) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.3.15, Copyright (c) 1998-2018 Zend Technologies

$ php -n /tmp/bench.php 
Function call isset took 0.59805 seconds
Function call array_key_exists took 0.71361 seconds
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment