- microtime: documentation ( source)
- str_repeat: documentation ( source)
- round: documentation ( source)
- serialize: documentation ( source)
- min: documentation ( source)
- json_encode: documentation ( source)
<?php
function acceptOne($a) {};
$str = str_repeat('abcd', 64 * 1024); // 256 KiB length
$benchFx = function (string $msg, \Closure $fx) {
$times = [];
for ($i = 0; $i < 10; $i++) {
$t = microtime(true);
$fx();
$t = microtime(true) - $t;
$times[] = $t;
}
$bestTime = min($times);
echo $msg . ': ' . round($bestTime * 1000, 2) . " ms\n";
};
$benchFx('json_encode', function () use ($str) {
for ($i = 0; $i < 200; $i++) {
$res = json_encode($str);
acceptOne($res);
}
});
$benchFx('serialize', function () use ($str) {
for ($i = 0; $i < 200; $i++) {
$res = serialize($str);
acceptOne($res);
}
});