Speed difference in using inline strings vs concatenation in php5?

The performance difference has been irrelevant since at least January 2012, and likely earlier:

Single quotes: 0.061846971511841 seconds
Double quotes: 0.061599016189575 seconds

Earlier versions of PHP may have had a difference - I personally prefer single quotes to double quotes, so it was a convenient difference. The conclusion of the article makes an excellent point:

Never trust a statistic you didn’t forge yourself.

(Although the article quotes the phrase, the original quip was likely falsely attributed to Winston Churchill, invented by Joseph Goebbels' propaganda ministry to portray Churchill as a liar:

Ich traue keiner Statistik, die ich nicht selbst gefälscht habe.

This loosely translates to, "I do not trust a statistic that I did not fake myself.")


Well, as with all "What might be faster in real life" questions, you can't beat a real life test.

function timeFunc($function, $runs)
{
  $times = array();

  for ($i = 0; $i < $runs; $i++)
  {
    $time = microtime();
    call_user_func($function);
    $times[$i] = microtime() - $time;
  }

  return array_sum($times) / $runs;
}

function Method1()
{ 
  $foo = 'some words';
  for ($i = 0; $i < 10000; $i++)
    $t = "these are $foo";
}

function Method2()
{
  $foo = 'some words';
  for ($i = 0; $i < 10000; $i++)
    $t = "these are {$foo}";
}

function Method3()
 {
  $foo = 'some words';
  for ($i = 0; $i < 10000; $i++)
    $t = "these are " . $foo;
}

print timeFunc('Method1', 10) . "\n";
print timeFunc('Method2', 10) . "\n";
print timeFunc('Method3', 10) . "\n";

Give it a few runs to page everything in, then...

0.0035568

0.0035388

0.0025394

So, as expected, the interpolation are virtually identical (noise level differences, probably due to the extra characters the interpolation engine needs to handle). Straight up concatenation is about 66% of the speed, which is no great shock. The interpolation parser will look, find nothing to do, then finish with a simple internal string concat. Even if the concat were expensive, the interpolator will still have to do it, after all the work to parse out the variable and trim/copy up the original string.

Updates By Somnath:

I added Method4() to above real time logic.

function Method4()
 {
  $foo = 'some words';
  for ($i = 0; $i < 10000; $i++)
    $t = 'these are ' . $foo;
}

print timeFunc('Method4', 10) . "\n";

Results were:

0.0014739
0.0015574
0.0011955
0.001169

When you are just declaring a string only and no need to parse that string too, then why to confuse PHP debugger to parse. I hope you got my point.