string concatenation (with single quotes) vs sprintf

hett's picture
Submitted by hett on Fri, 08/03/2012 - 14:59

f2 is slower than f1 by 163.72% (1.6 times slower)

Full source code as executed.
/* How many times the code under test should run in each function */
define('LOOP',1000000);
 
function f1() {
  $var = NULL;
  for($i=0; $i<LOOP; ++$i) {
    $var = 'test'.'123'.'string';
  }
}
function f2() {
  $var = NULL;
  for($i=0; $i<LOOP; ++$i) {
    $var = sprintf('test%sstring', 123);
  }
}
$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
242.91%74301625478935.3.3-7+squeeze1
149.72%114452285809php-5.3.6-phpbrew_compiled
156.65%113844292185php-5.3.7-phpbrew_compiled
142.87%115368280189php-5.3.8-phpbrew_compiled
137.47%115807275010php-5.3.9-phpbrew_compiled
121.11%124107274412php-5.3.10-phpbrew_compiled
175.94%106832294789php-5.3.11-phpbrew_compiled
175.02%107211294852php-5.3.12-phpbrew_compiled
172.94%108053294918php-5.3.13-phpbrew_compiled
122.35%123813275301php-5.3.14-phpbrew_compiled
172.62%109746299189php-5.3.15-phpbrew_compiled
125.51%125813283724php-5.3.16-phpbrew_compiled
158.52%109976284308php-5.3.17-phpbrew_compiled
186.46%109089312494php-5.3.18-phpbrew_compiled
163.58%108238285292php-5.3.19-phpbrew_compiled
183.25%82502233689php-5.4.0-phpbrew_compiled
146.28%102327252008php-5.4.1-phpbrew_compiled
157.9%95870247246php-5.4.2-phpbrew_compiled
147.2%102128252459php-5.4.3-phpbrew_compiled
169.74%87289235450php-5.4.4-phpbrew_compiled
187.29%86622248858php-5.4.5-phpbrew_compiled
182.67%83471235948php-5.4.6-phpbrew_compiled
183.98%83197236267php-5.4.7-phpbrew_compiled
173.62%84585231445php-5.4.8-phpbrew_compiled
157.37%96541248467php-5.4.9-phpbrew_compiled
50%
updown
50%

Comments

Submitted by Hani on Wed, 08/08/2012 - 18:04

I've removed call to print from both functions - this should make no difference for the comparison.  print('test'.'123'.'string');
changed to:
 $var = 'test'.'123'.'string';
and
 print(sprintf('test%sstring', 123));
changed to:
 $var = sprintf('test%sstring', 123);