Skip to content

Instantly share code, notes, and snippets.

@appkr
Created May 4, 2017 03:33
Show Gist options
  • Save appkr/b311fd56fd7d52ee092c2b95a5a82bc6 to your computer and use it in GitHub Desktop.
Save appkr/b311fd56fd7d52ee092c2b95a5a82bc6 to your computer and use it in GitHub Desktop.
Associative Array methods profiling
<?php
// Code referenced from https://gist.github.com/Thinkscape/1965669
if (!isset($argv[1])) {
echo "Usage: " . $argv[0] . " (number of iterations)\n";
exit(1);
}
$tests = [
[
[
'foo' => 'bar',
],
],
[
[
'bar',
'foo' => 'bar',
'baz',
],
],
[null],
[true],
[false],
[0],
[1],
[0.0],
[1.0],
['string'],
[
[0, 1, 2],
],
[new stdClass],
array_fill(0, 1000, uniqid()), // big numeric array
array_fill_keys(range(2, 1000, 3), uniqid()), // big misaligned numeric array (=associative)
array_fill_keys( // big associative array
str_split(
str_repeat(uniqid('', true), 100),
3
),
true
),
];
$iterations = (int) $argv[1];
$methods = [
'method1 (array_values check)' =>
function ($array) {
return (array_values($array) !== $array);
},
'method2 (array_keys comparison)' =>
function ($array) {
$array = array_keys($array);
return ($array !== array_keys($array));
},
'method3 (array_filter of keys)' =>
function ($array) {
return count(array_filter(array_keys($array), 'is_string')) > 0;
},
'method4 (appkr)' =>
function ($array) {
return array_keys($array) !== range(0, count($array) - 1);
},
];
foreach ($methods as $name => $func) {
echo "Testing $name - $iterations iterations\n";
$time = microtime(true);
for ($x = 0; $x < $iterations; $x++) {
foreach ($tests as $array) {
$func($array);
}
}
$totalTime = (microtime(true) - $time);
$avgTime = $totalTime / ($iterations * count($tests));
$memoryUsageAtEachTurn[] = memory_get_usage() / 1000000;
$avgMemoryUsage = array_sum($memoryUsageAtEachTurn) / count($memoryUsageAtEachTurn);
echo " Total time: " . number_format($totalTime, 5, '.', ' ') . " s\n";
echo " Average : " . number_format($avgTime * 1000, 5, '.', ' ') . " ms / test \n";
echo " Memory usage : " . number_format($avgMemoryUsage, 5, '.', ' ') . " Mbytes / test \n";
echo "\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment