strtr() vs str_replace()

Submitted by mattg on Wed, 11/14/2012 - 10:51

f2 is slower than f1 by 9.76%

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) {
    $new_string = strtr("test_string_with_underscores", "_", " ");
  }
}
function f2() {
  for($i=0; $i<LOOP; ++$i) {
    $new_string = str_replace("_", " ", "test_string_with_underscores");
  }
}
$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
5.55%267890625380615.3.3-7+squeeze1
11.1%332140369006php-5.3.6-phpbrew_compiled
9.12%348887380713php-5.3.7-phpbrew_compiled
10.11%339577373917php-5.3.8-phpbrew_compiled
13.64%330699375796php-5.3.9-phpbrew_compiled
11.15%341153379183php-5.3.10-phpbrew_compiled
12.77%333565376177php-5.3.11-phpbrew_compiled
12.88%337480380962php-5.3.12-phpbrew_compiled
12.87%333453376360php-5.3.13-phpbrew_compiled
14.87%328778377676php-5.3.14-phpbrew_compiled
3.67%357309370437php-5.3.15-phpbrew_compiled
12.32%333569374654php-5.3.16-phpbrew_compiled
18.26%324170383360php-5.3.17-phpbrew_compiled
10.12%363914400760php-5.3.18-phpbrew_compiled
19.09%323434385164php-5.3.19-phpbrew_compiled
12.61%265213298647php-5.4.0-phpbrew_compiled
5.73%280769296862php-5.4.1-phpbrew_compiled
7.08%275730295250php-5.4.2-phpbrew_compiled
5.71%281554297623php-5.4.3-phpbrew_compiled
8.47%260212282240php-5.4.4-phpbrew_compiled
12.79%274420309529php-5.4.5-phpbrew_compiled
6.52%272267290017php-5.4.6-phpbrew_compiled
7.84%265640286465php-5.4.7-phpbrew_compiled
3.93%268664279216php-5.4.8-phpbrew_compiled
6.97%277027296340php-5.4.9-phpbrew_compiled
50%
updown
50%