public
Last active

A benchmark of several methods for checking if PHP array is associative

  • Download Gist
isAssocArrayBench.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
<?php
if(!isset($argv[1])){
echo "Usage: ".$argv[0]." (number of iterations)\n";
exit(1);
}
 
/**
* 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
)
);
 
$iterations = (int)$argv[1];
 
/**
* Common methods to check associative array
*/
$methods = array(
'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;
}
);
 
/**
* Perform benchmark on each method
*/
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);
}
}
 
/**
* 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";
}

PHP 5.3.6 on Ubuntu, running at Core 2 Duo laptop:

$ php isAssocArrayBench.php 10000
Testing method1 (array_values check) - 10000 iterations
  Total time: 4.01563 s
  Average   : 0.02677 ms / test 

Testing method2 (array_keys comparison) - 10000 iterations
  Total time: 12.11279 s
  Average   : 0.08075 ms / test 

Testing method3 (array_filter of keys) - 10000 iterations
  Total time: 16.43639 s
  Average   : 0.10958 ms / test 

Beware that the fastest method should consume more memory while the GC doesn't kicks in.

@alixaxel That is correct, it will consume a little bit more memory than method 2 - but that's temporary usage per each fn call (per test) and becomes visible only for flat, long arrays (say 1000+ keys).

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.