Skip to content

Instantly share code, notes, and snippets.

@KVytyagov
Last active March 13, 2020 10:38
Show Gist options
  • Select an option

  • Save KVytyagov/b9ce9d3f373e87053e729f9e7a561018 to your computer and use it in GitHub Desktop.

Select an option

Save KVytyagov/b9ce9d3f373e87053e729f9e7a561018 to your computer and use it in GitHub Desktop.
Test performance of isset, array_key_exists, isset OR array_key_exists on NULL-array item
<?php
$a = null;
$key = null;
$startIdx = 0;
$func = function() use (&$a, &$key, &$startIdx) {
$a = array_fill_keys(range($startIdx, $startIdx+=1000), null);
$key = $startIdx + 1;
};
$iterations = 10;
$count = 1000000;
$avg = [];
$func();
$name = 'isset';
for ($j = 0; $j < $iterations; ++$j) {
$start = microtime(true);
for ($i = 0; $i<$count; ++$i) {
isset($a[$key]);
}
$time = microtime(true) - $start;
$avg[$name][] = $time;
echo $name . ': ' . $time . "\n";
}
$func();
$name = 'array_key_exists';
for ($j = 0; $j < $iterations; ++$j) {
$start = microtime(true);
for ($i = 0; $i<$count; ++$i) {
array_key_exists($key, $a);
}
$time = microtime(true) - $start;
$avg[$name][] = $time;
echo $name . ': ' . $time . "\n";
}
$func();
$name = 'isset || array_key_exists';
for ($j = 0; $j < $iterations; ++$j) {
$start = microtime(true);
for ($i = 0; $i<$count; ++$i) {
isset($a[$key]) || array_key_exists($key, $a);
}
$time = microtime(true) - $start;
$avg[$name][] = $time;
echo $name . ': ' . $time . "\n";
}
$func();
$a = array_keys($a);
$name = 'in_array';
for ($j = 0; $j < $iterations; ++$j) {
$start = microtime(true);
for ($i = 0; $i<$count; ++$i) {
in_array($key, $a);
}
$time = microtime(true) - $start;
$avg[$name][] = $time;
echo $name . ': ' . $time . "\n";
}
$func();
$a = array_keys($a);
$name = 'in_array_strict';
for ($j = 0; $j < $iterations; ++$j) {
$start = microtime(true);
for ($i = 0; $i<$count; ++$i) {
in_array($key, $a, true);
}
$time = microtime(true) - $start;
$avg[$name][] = $time;
echo $name . ': ' . $time . "\n";
}
foreach ($avg as $name => $times) {
echo $name . ' [AVG]: ' . \array_sum($times)/\count($times) . "\n";
}
@KVytyagov
Copy link
Author

PHP 7.2.28-3+ubuntu18.04.1+deb.sury.org+1 (cli) (built: Feb 23 2020 07:23:25) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies
    with Zend OPcache v7.2.28-3+ubuntu18.04.1+deb.sury.org+1, Copyright (c) 1999-2018, by Zend Technologies
    with Xdebug v2.9.2, Copyright (c) 2002-2020, by Derick Rethans
isset [AVG]: 0.20750651359558
array_key_exists [AVG]: 0.88147220611572
isset || array_key_exists [AVG]: 0.97458655834198
in_array [AVG]: 5.1713105201721
in_array_strict [AVG]: 9.7148007154465

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