str_replace vs implode explode

kgruszczynski's picture
Submitted by kgruszczynski on Thu, 03/22/2012 - 00:40

f1 is slower than f2 by 135.91% (1.4 times slower)

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) {
   $z=implode( "-",explode( " ", strtolower("aaa bbbb cccc" ) ) );
  }
}
function f2() {
  for($i=0; $i<LOOP; ++$i) {
   $z=str_replace(" ","-","aaa bbbb cccc");
  }
}
$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
148.1%719319428993095.3.3-7+squeeze1
122.35%829277372955php-5.3.6-phpbrew_compiled
120.38%808974367084php-5.3.7-phpbrew_compiled
130.78%827054358372php-5.3.8-phpbrew_compiled
127.49%877197385601php-5.3.9-phpbrew_compiled
122.62%812573365012php-5.3.10-phpbrew_compiled
122.05%827679372743php-5.3.11-phpbrew_compiled
121.99%824058371221php-5.3.12-phpbrew_compiled
122.39%832805374480php-5.3.13-phpbrew_compiled
134.77%888387378403php-5.3.14-phpbrew_compiled
135.24%882907375326php-5.3.15-phpbrew_compiled
128.15%848028371704php-5.3.16-phpbrew_compiled
129.8%880404383111php-5.3.17-phpbrew_compiled
124.06%901480402331php-5.3.18-phpbrew_compiled
120.19%864319392526php-5.3.19-phpbrew_compiled
143.08%699947287946php-5.4.0-phpbrew_compiled
143.19%738177303537php-5.4.1-phpbrew_compiled
156.4%770456300487php-5.4.2-phpbrew_compiled
145.24%767869313108php-5.4.3-phpbrew_compiled
159.69%716611275944php-5.4.4-phpbrew_compiled
127.81%704428309220php-5.4.5-phpbrew_compiled
156.56%713480278093php-5.4.6-phpbrew_compiled
144.94%699560285610php-5.4.7-phpbrew_compiled
167.16%738285276345php-5.4.8-phpbrew_compiled
143.32%713631293287php-5.4.9-phpbrew_compiled
50%
updown
50%