<?php
function pure_regex() {
$result = preg_replace('/\G(?:^|(?(?<!^.).)..(?:.{4})*?)\Kr/s', 'M', 'it is a test string.'); }
function with_callback() {
return $m[0] == 'r' ? 'M' : $m[0];
}, 'it is a test string.');
}
function no_regex() {
$str ='it is a test string.';
if($str[0]=='r') $str[0] = 'M';
for($i=3; $i<$len; $i+=4)
if($str[$i] == 'r')
$str[$i] = 'M';
}
function regex_array() {
$result = preg_replace(['/^r/', '/\G(?:.{3}[^r])*+.{3}\Kr/s'], 'M', 'it is a test string.'); }
$best = 999999999;
$worst = 0;
$best_num = -1;
function speed_test($code, $loops = 500000) {
for ($i=0 ; $i<$loops ; $i++) {
$code();
}
$delay = $after-$before;
return $delay;
}
// --------
$names = ['with_callback', 'regex_array', 'no_regex', 'pure_regex'];
$loops = 50000;
foreach ($names as $code_num => $f)
{
$delay = speed_test($f, $loops);
if ($delay < $best) {
$best = $delay;
$best_num = $code_num;
}
if ($delay > $worst) {
$worst = $delay;
}
echo 'Code #' . ($code_num + 1) . "($names[$code_num]): \t" . number_format($delay, 3) . " secs/" . $loops/1E3 . "k loops\n"; }
echo "BEST: $names[$best_num] by " . number_format((1- $best / $worst) * 100, 0) . "% over worst case";
?>
PD9waHAKCmZ1bmN0aW9uIHB1cmVfcmVnZXgoKSB7CgkkcmVzdWx0ID0gcHJlZ19yZXBsYWNlKCcvXEcoPzpefCg/KD88IV4uKS4pLi4oPzouezR9KSo/KVxLci9zJywgJ00nLCAnaXQgaXMgYSB0ZXN0IHN0cmluZy4nKTsKfQpmdW5jdGlvbiB3aXRoX2NhbGxiYWNrKCkgewoJJHJlc3VsdCA9IHByZWdfcmVwbGFjZV9jYWxsYmFjayhbJy9eLi8nLCAnLy57M31cSy4vJ10sIGZ1bmN0aW9uICgkbSkgewogICAgICAgICByZXR1cm4gJG1bMF0gPT0gJ3InID8gJ00nIDogJG1bMF07CiAgICAgICB9LCAnaXQgaXMgYSB0ZXN0IHN0cmluZy4nKTsKfQpmdW5jdGlvbiBub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