string concatenation (with double quotes) vs sprintf

hett's picture
Submitted by hett on Fri, 08/03/2012 - 15:01

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

Full source code as executed.
/* How many times the code under test should run in each function */
define('LOOP',100000);
$a = '123';
function f1() {
  global $a;
  $var = NULL;
  for($i=0; $i<LOOP; ++$i) {
    $var = "test{$a}string";
  }
}
function f2() {
  global $a;
  $var = NULL;
  for($i=0; $i<LOOP; ++$i) {
    $var = sprintf('test%sstring', $a);
  }
}
$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
194.75%727652144785.3.3-7+squeeze1
95.87%1360626650php-5.3.6-phpbrew_compiled
98.24%1347426711php-5.3.7-phpbrew_compiled
131.31%1142926436php-5.3.8-phpbrew_compiled
147.15%1054026050php-5.3.9-phpbrew_compiled
145.95%1052725891php-5.3.10-phpbrew_compiled
182.81%996428179php-5.3.11-phpbrew_compiled
177.95%1006327970php-5.3.12-phpbrew_compiled
157.01%1080027757php-5.3.13-phpbrew_compiled
70.85%1536326248php-5.3.14-phpbrew_compiled
119.63%1200126358php-5.3.15-phpbrew_compiled
106.33%1294626712php-5.3.16-phpbrew_compiled
144.1%1089526595php-5.3.17-phpbrew_compiled
155.51%1155629527php-5.3.18-phpbrew_compiled
151.95%1065826853php-5.3.19-phpbrew_compiled
144.12%770818817php-5.4.0-phpbrew_compiled
115.02%929219980php-5.4.1-phpbrew_compiled
124.8%861719371php-5.4.2-phpbrew_compiled
114.15%936820062php-5.4.3-phpbrew_compiled
150.1%749918755php-5.4.4-phpbrew_compiled
165.03%751319912php-5.4.5-phpbrew_compiled
148.56%746118545php-5.4.6-phpbrew_compiled
110.82%866018257php-5.4.7-phpbrew_compiled
164.5%749019811php-5.4.8-phpbrew_compiled
150.47%863221621php-5.4.9-phpbrew_compiled
50%
updown
50%

Comments

Submitted by admin on Wed, 08/08/2012 - 18:15

I've removed call to print from both functions - this should make no difference for the comparison.
 print("test{$a}string");
changed to:
 $var = "test{$a}string";
and
 print(sprintf('test%sstring', $a));
changed to:
 $var = sprintf('test%sstring', $a);
I also added missing global $a;