fork download
  1. <?php
  2.  
  3. function pure_regex() {
  4. $result = preg_replace('/\G(?:^|(?(?<!^.).)..(?:.{4})*?)\Kr/s', 'M', 'it is a test string.');
  5. }
  6. function with_callback() {
  7. $result = preg_replace_callback(['/^./', '/.{3}\K./'], function ($m) {
  8. return $m[0] == 'r' ? 'M' : $m[0];
  9. }, 'it is a test string.');
  10. }
  11. function no_regex() {
  12. $str ='it is a test string.';
  13. $len = strlen($str);
  14. if($str[0]=='r') $str[0] = 'M';
  15. for($i=3; $i<$len; $i+=4)
  16. if($str[$i] == 'r')
  17. $str[$i] = 'M';
  18. }
  19. function regex_array() {
  20. $result = preg_replace(['/^r/', '/\G(?:.{3}[^r])*+.{3}\Kr/s'], 'M', 'it is a test string.');
  21. }
  22.  
  23. $best = 999999999;
  24. $worst = 0;
  25. $best_num = -1;
  26. function speed_test($code, $loops = 500000) {
  27. $before = microtime(true);
  28. for ($i=0 ; $i<$loops ; $i++) {
  29. $code();
  30. }
  31. $after = microtime(true);
  32. $delay = $after-$before;
  33. return $delay;
  34. }
  35.  
  36. // --------
  37.  
  38. $names = ['with_callback', 'regex_array', 'no_regex', 'pure_regex'];
  39. $loops = 50000;
  40.  
  41. foreach ($names as $code_num => $f)
  42. {
  43. $delay = speed_test($f, $loops);
  44. if ($delay < $best) {
  45. $best = $delay;
  46. $best_num = $code_num;
  47. }
  48. if ($delay > $worst) {
  49. $worst = $delay;
  50. }
  51. echo 'Code #' . ($code_num + 1) . "($names[$code_num]): \t" . number_format($delay, 3) . " secs/" . $loops/1E3 . "k loops\n";
  52. }
  53. echo "BEST: $names[$best_num] by " . number_format((1- $best / $worst) * 100, 0) . "% over worst case";
  54.  
  55. ?>
Success #stdin #stdout 0.96s 52472KB
stdin
Standard input is empty
stdout
Code #1(with_callback): 	0.548 secs/50k loops
Code #2(regex_array): 	0.158 secs/50k loops
Code #3(no_regex): 	0.120 secs/50k loops
Code #4(pure_regex): 	0.118 secs/50k loops
BEST: pure_regex by 78% over worst case