Create a gist now

Instantly share code, notes, and snippets.

<?php
function benchmark($title, $loop = 1, callable $target)
{
echo '# ' . $title, PHP_EOL;
$start = microtime(true);
for ($i = 0; $i < $loop; $i++) {
$target();
}
echo (microtime(true) - $start) / $loop, PHP_EOL;
echo PHP_EOL;
}
function benchmark_loop($title, callable $target)
{
foreach ([20, 200, 2000, 20000, 200000] as $no) {
$string = str_repeat(' ', $no) . 'a';
benchmark($title . ' - ' . $no, 3, function () use ($string, $target) {
return $target($string);
});
}
}
benchmark_loop('\s+$', function ($string) {
return preg_replace('/\s+$/', '', $string);
});
benchmark_loop('\s++$', function ($string) {
return preg_replace('/\s++$/', '', $string);
});
benchmark_loop('rtrim', function ($string) {
return rtrim($string);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment