Last active
April 20, 2020 14:56
-
-
Save bcremer/5078e44294a3b8d6b89b4efbc23d9a3b to your computer and use it in GitHub Desktop.
Measure array unpack vs. array_merge
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Array Unpack | |
user: 4.355 ms | |
system: 0 ms | |
wait: 25 ms | |
total: 4.381 ms | |
Array Merge | |
user: 6.798 ms | |
system: 0 ms | |
wait: 7 ms | |
total: 6.805 ms |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$measure = static function (callable $lambda) { | |
$startHrTime = hrtime(true); | |
$rUsage = getrusage(); | |
$startUTime = $rUsage['ru_utime.tv_usec'] + $rUsage['ru_utime.tv_sec'] * 1000000; | |
$startSTime = $rUsage['ru_stime.tv_usec'] + $rUsage['ru_stime.tv_sec'] * 1000000; | |
$lambda(); | |
$rUsage = getrusage(); | |
$user = ($rUsage['ru_utime.tv_usec'] + $rUsage['ru_utime.tv_sec'] * 1000000 - $startUTime) / 1000; | |
$system = ($rUsage['ru_stime.tv_usec'] + $rUsage['ru_stime.tv_sec'] * 1000000 - $startSTime) / 1000; | |
$total = (hrtime(true) - $startHrTime) / 1000000; | |
$wait = $total - ($user + $system); | |
$measurements = [ | |
'user' => $user, | |
'system' => $system, | |
'wait' => $wait, | |
'total' => $total, | |
]; | |
$format = static function (float $timeInMs) { | |
return str_pad(number_format($timeInMs, 0, ',', '.') . ' ms', 10, ' ', STR_PAD_LEFT); | |
}; | |
foreach ($measurements as $header => $value) { | |
echo "${header}:\t" . $format($value) . PHP_EOL; | |
} | |
echo PHP_EOL; | |
}; | |
const REPEAT = 100000000; | |
echo "Array Unpack\n"; | |
$measure(static function () { | |
$item = 'foo'; | |
$items = ['bar', 'baz']; | |
for ($x = 0; $x < REPEAT; ++$x) { | |
$foo = [$item, ...$items]; | |
} | |
}); | |
echo "Array Merge\n"; | |
$measure(static function () { | |
$item = 'foo'; | |
$items = ['bar', 'baz']; | |
for ($x = 0; $x < REPEAT; ++$x) { | |
$foo = array_merge([$item], $items); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment