Last active
March 13, 2020 10:38
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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"; | |
| } |
Author
KVytyagov
commented
Mar 13, 2020
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment