Skip to content

Instantly share code, notes, and snippets.

@icio
Last active August 29, 2015 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save icio/ebb8c666815054ffea7e to your computer and use it in GitHub Desktop.
Save icio/ebb8c666815054ffea7e to your computer and use it in GitHub Desktop.
Array merge benchmark
<?php
/*
$ php ~/test.php
Runs: 100,000
Benchmark Avg (s) Total (s)
---------- ---------- ----------
sum 0.000006 0.597605
merge 0.000007 0.713410
*/
$count = 100000;
timethem(array(
'sum' => function() {
return array('q' => null) + array('q' => '/123', 'p' => 'test');
},
'merge' => function() {
return array_merge(
array('q' => '/123', 'p' => 'test'),
array('q' => null)
);
},
), $count);
function timethem(array $tests, $count)
{
echo 'Runs: ', number_format($count), "\n\n";
echo sprintf("%-10s %-10s %-10s\n", 'Benchmark', 'Avg (s)', 'Total (s)');
echo sprintf("%'-10s %'-10s %'-10s\n", '', '', '');
foreach ($tests as $name => $test) {
list($total, $avg) = timeit($test, $count);
echo sprintf(
"%10s %10f %10f\n",
$name, $avg, $total
);
}
}
function timeit($test, $count)
{
$start = microtime(true);
for ($i = 0; $i < $count; $i++) {
call_user_func($test);
}
$total = microtime(true) - $start;
return array($total, $total / $count);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment