Skip to content

Instantly share code, notes, and snippets.

@elliotchance
Created July 24, 2015 02:13
Show Gist options
  • Save elliotchance/b17e4fef1d58e7d786dc to your computer and use it in GitHub Desktop.
Save elliotchance/b17e4fef1d58e7d786dc to your computer and use it in GitHub Desktop.
in_array() vs array_key_exists()
Time shows total time for 1024 iterations
Size | in_array | array_key_exists
1 | 0.000 | 0.000
2 | 0.001 | 0.000
4 | 0.001 | 0.000
8 | 0.001 | 0.001
16 | 0.001 | 0.000
32 | 0.001 | 0.000
64 | 0.001 | 0.000
128 | 0.002 | 0.001
256 | 0.003 | 0.000
512 | 0.007 | 0.001
1024 | 0.013 | 0.001
2048 | 0.030 | 0.000
4096 | 0.048 | 0.001
8192 | 0.079 | 0.001
16384 | 0.140 | 0.001
32768 | 0.181 | 0.001
<?php
echo "Time shows total time for 1024 iterations\n\n";
echo "Size | in_array | array_key_exists\n";
for ($size = 1; $size <= 32768; $size *= 2) {
$a = [];
for ($i = 0; $i < $size; ++$i) {
$a[] = $i;
}
$start = microtime(true);
for ($i = 0; $i < 1024; ++$i) {
in_array($i * 32, $a);
}
$time1 = microtime(true) - $start;
$a = [];
for ($i = 0; $i < $size; ++$i) {
$a[$i] = 1;
}
$start = microtime(true);
for ($i = 0; $i < 1024; ++$i) {
array_key_exists($i * 32, $a);
}
$time2 = microtime(true) - $start;
printf("%7d | %8.3f | %.3f\n", $size, $time1, $time2);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment