str_replace vs preg_replace (without regular expression)

Submitted by Lito on Fri, 03/16/2012 - 15:48

f2 is slower than f1 by 61.56%

Full source code as executed.
/* How many times the code under test should run in each function */
define('LOOP',1000000);
 
function f1() {
  for($i=0; $i<LOOP; ++$i) {
    str_replace('_', '-', 'parse-url-without-regular-expression');
  }
}
function f2() {
  for($i=0; $i<LOOP; ++$i) {
    preg_replace('/_/', '-', 'parse-url-without-regular-expression');
  }
}
$start = microtime(true);
f1();
$stop = microtime(true);
$time1 = $stop - $start;
 
$start = microtime(true);
f2();
$stop = microtime(true);
$time2 = $stop - $start;
 
echo $time1 . "\t";
echo $time2 . "\n";
Test results
comparisontime1time2php_version
40.33%266869737450795.3.3-7+squeeze1
59.93%281945450905php-5.3.6-phpbrew_compiled
60.85%281712453125php-5.3.7-phpbrew_compiled
57%284446446586php-5.3.8-phpbrew_compiled
54%293410451851php-5.3.9-phpbrew_compiled
62.84%294002478758php-5.3.10-phpbrew_compiled
62.22%292177473959php-5.3.11-phpbrew_compiled
60.53%291342467680php-5.3.12-phpbrew_compiled
61.88%294183476237php-5.3.13-phpbrew_compiled
59.65%283080451934php-5.3.14-phpbrew_compiled
55.46%288852449038php-5.3.15-phpbrew_compiled
63.75%284319465574php-5.3.16-phpbrew_compiled
50.36%299028449623php-5.3.17-phpbrew_compiled
56.97%317073497704php-5.3.18-phpbrew_compiled
55.9%299364466718php-5.3.19-phpbrew_compiled
79.7%222681400154php-5.4.0-phpbrew_compiled
55.04%254238394180php-5.4.1-phpbrew_compiled
77.06%233689413778php-5.4.2-phpbrew_compiled
55.01%263283408117php-5.4.3-phpbrew_compiled
71.51%221590380057php-5.4.4-phpbrew_compiled
65.37%238781394881php-5.4.5-phpbrew_compiled
78.26%219637391516php-5.4.6-phpbrew_compiled
65.66%223210369760php-5.4.7-phpbrew_compiled
66.86%219069365530php-5.4.8-phpbrew_compiled
62.95%232446378782php-5.4.9-phpbrew_compiled
50%
updown
50%