fork download
  1. <?php
  2.  
  3. bcscale(15);
  4.  
  5. function letterSequencePregSplit($string) {
  6. $stringAsArray = preg_split('//u', $string, null, PREG_SPLIT_NO_EMPTY);
  7. $arrayCount = count($stringAsArray);
  8.  
  9. for ($i = 0; $i < $arrayCount; $i++) {
  10. yield $stringAsArray[$i];
  11. }
  12. }
  13.  
  14. function letterSequenceMbSubstr($string) {
  15. $stringLength = mb_strlen($string);
  16.  
  17. for ($i = 0; $i < $stringLength; $i++) {
  18. yield mb_substr($string, $i, 1);
  19. }
  20. }
  21.  
  22. function getAverageDurationFor(callable $generator, $string, $attempts = 1000) {
  23. $timeOverall = 0;
  24.  
  25. for ($i = 0; $i < $attempts; $i++) {
  26. $timeStart = microtime(true);
  27. foreach ($generator($string) as $letter) {}
  28. $timeEnd = microtime(true);
  29. $timeOverall = bcadd($timeOverall, bcsub($timeEnd, $timeStart));
  30. }
  31.  
  32. return bcdiv($timeOverall, $attempts);
  33. }
  34.  
  35. function doBenchmark($startLength, $endLength, $step) {
  36. $string = 'å';
  37. for ($length = $startLength; $length < $endLength; $length += $step) {
  38. echo sprintf("string length: %s\n", $length);
  39. echo sprintf("preg_split: %s\n", getAverageDurationFor('letterSequencePregSplit', str_repeat($string, $length)));
  40. echo sprintf("mb_substr: %s\n\n", getAverageDurationFor('letterSequenceMbSubstr', str_repeat($string, $length)));
  41. }
  42. }
  43.  
  44. doBenchmark(1, 500, 50);
  45.  
Success #stdin #stdout 2.74s 52488KB
stdin
Standard input is empty
stdout
string length: 1
preg_split: 0.000001400000000
mb_substr:  0.000000500000000

string length: 51
preg_split: 0.000021300000000
mb_substr:  0.000018700000000

string length: 101
preg_split: 0.000041500000000
mb_substr:  0.000044100000000

string length: 151
preg_split: 0.000059800000000
mb_substr:  0.000078200000000

string length: 201
preg_split: 0.000079500000000
mb_substr:  0.000119900000000

string length: 251
preg_split: 0.000095000000000
mb_substr:  0.000170600000000

string length: 301
preg_split: 0.000118000000000
mb_substr:  0.000230200000000

string length: 351
preg_split: 0.000140200000000
mb_substr:  0.000295700000000

string length: 401
preg_split: 0.000157800000000
mb_substr:  0.000376300000000

string length: 451
preg_split: 0.000179700000000
mb_substr:  0.000457400000000