Skip to content

Instantly share code, notes, and snippets.

@oriadam
Forked from Thinkscape/isAssocArrayBench.php
Last active May 19, 2021 10:43
Show Gist options
  • Save oriadam/5e8424608fb3f8d70ec3e9ae344dbf8f to your computer and use it in GitHub Desktop.
Save oriadam/5e8424608fb3f8d70ec3e9ae344dbf8f to your computer and use it in GitHub Desktop.
A benchmark of several methods for checking if PHP array is associative
<?php
$iterations = $argv[1] ?: 10000;
/**
* Arrays to check
*/
$tests = array(
array(array(
'foo' => 'bar',
)),
array(array(
'bar',
'foo' => 'bar',
'baz',
)),
array(null),
array(true),
array(false),
array(0),
array(1),
array(0.0),
array(1.0),
array('string'),
array(array(0, 1, 2)),
array(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
)
);
/**
* Common methods to check associative array
*/
$methods = array(
'if (array_key_first($array)!==0) return true; return array_values($array) !== $array;' =>
function ($array)
{
if (array_key_first($array) !== 0)
{
return true;
}
return array_values($array) !== $array;
},
'return array_values($array) !== $array;' =>
function ($array)
{
return array_values($array) !== $array;
},
'return range(0,count($array)) !== array_keys($array);' =>
function ($array)
{
return range(0, count($array)) !== array_keys($array);
},
'array_keys($array); return $array !== array_keys($array);' =>
function ($array)
{
$array = array_keys($array);
return ($array !== array_keys($array));
},
'return count(array_filter(array_keys($array), "is_string")) > 0;' =>
function ($array)
{
return count(array_filter(array_keys($array), "is_string")) > 0;
},
'foreach...$i++' =>
function ($array)
{
$i = 0;
foreach ($array as $k => $v)
{
if ($i !== $k)
{
return true;
}
$i++;
}
return false;
},
// 'for...key...next' =>
// function ($array)
// {
// $l = count($array);
// for ($i = 0; $i < $l; $i++)
// {
// if (key($array) !== $i)
// {
// return true;
// }
// next($array);
// }
// return false;
// },
);
/**
* Perform benchmark on each method
*/
echo "Testing $iterations iterations on PHP version ".phpversion()."\n";
foreach ($methods as $name => $func)
{
echo "$name\n";
$time = microtime(true);
for ($x = 0; $x < $iterations; $x++)
{
foreach ($tests as $array)
{
$func($array);
}
}
/**
* Show results
*/
$totalTime = (microtime(true) - $time);
$avgTime = $totalTime / ($iterations * count($tests));
echo " Total time: " . number_format($totalTime, 5, '.', ' ') . " s\n";
echo " Average : " . number_format($avgTime * 1000, 5, '.', ' ') . " ms / test \n";
echo "\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment