Speed difference in using inline strings vs concatenation in php5?
Asked Answered
S

15

57

(assume php5) consider

<?php

    $foo = 'some words';

    //case 1
    print "these are $foo";

    //case 2
    print "these are {$foo}";

    //case 3
    print 'these are ' . $foo;
?>

Is there much of a difference between 1 and 2?

If not, what about between 1/2 and 3?

Sasha answered 17/8, 2008 at 13:19 Comment(5)
Note that echo 'these are ', $foo; is faster than any of those, since there is no concatenation or interpolation.Barrelhouse
Why on Earth is this question not constructive?Cutwork
No idea. It was really a seed question, added shortly after the start of the site, when the beta people were encouraged to post baseline questions that would come up in early google searches, even if they were far too simple of a question, or bordering on non-question form. Given the views and activity of comments and voting therein, I'd say it was pretty constructive, imho.Sasha
Please see my answer to another question, where this issue has come up in comments: https://mcmap.net/q/102847/-how-to-add-php-variable-in-url-name-not-in-url-link-closedCallas
Single quotes are faster in my scenario. I run asynchronous log parsers using parallel, the performance boost in CPU gave-me the oportunity to run more parsers in parallel. Single quoted I can parse 144TB/hour double quoted I can parse less than 95TB. But you will only need to check it when you already did all of the things you could === instead of ==, string comparsion instead of regex and tons of others.Cumine
W
45

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.

Winters answered 17/8, 2008 at 15:10 Comment(5)
Surely you can't beat a real life test. But this artificial frankenstein has nothing in common with the real life conditions.Cubage
Those skeptics trying to reproduce these results (like me ;-) on PHP5+ change the microtime() calls to microtime(true) - you want the time as a float, not as some sort of weird string.Gujarat
Added Method4() for string processing. And I think PHP processing got more faster now. @AdamWrightThromboplastin
Hello. Your comparison assumes that there is but a single instance of the variable within a string. Please see https://mcmap.net/q/102847/-how-to-add-php-variable-in-url-name-not-in-url-link-closedCallas
This confuses me: "about 66% of the speed", ain't that "about 66% of the time"? I thought concatenation is faster?Massarelli
M
108

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.")

Mirthless answered 17/8, 2008 at 13:19 Comment(15)
Although the performance difference is a few milliseconds... but I suppose it can add upKirkkirkcaldy
Wouldn't this just be a compile-time check?Nari
Wow, I can't believe I didn't know this and was about to make fun of the question... is there any way to get your single quoted string to be parsed again?Reduced
And, on top of that, by using less pixels, you reduce greenhouse emissions.Armin
"Wouldn't this just be a compile-time check?"-nobody Why yes it would. It's a scripted language, so compile time is run time.Megasporophyll
Actually, since faster computation means less CPU time means less watts consumed, single quotes really do reduce greenhouse emissions.Venter
@Paolo Begantino: do you actually have any proof of this? phpbench.com respectfully disagrees with you every time I load it.Inion
@A.Rex: Mm. To be honest, I don't. I don't know if it has been handled in latest versions or what, my answer was just what I've picked up through time and what I reasoned. I'll look into it some more I guess.Mirthless
I've also found double quotes to be slightly faster. (Though my argument is always about readability, which double quotes win.)Eroticism
Your example is flawed, as it does no concatenation with single quotes.Milton
Note that even if you use a single-quoted string, PHP is still parsing over every character in it, to look for escape sequences, etc. PHP is also parsing the entire file, so at best, you're still looking at O(n) for the length of the string.Caritacaritas
@A. Rex: I think it all depends on the size of the string and the number of variable present in it. Double quote needs some time to parse variables; some variables could be a complex object which has a method toString()Scaphoid
This is incorrect in any modern install of PHP, and should be adjusted. There is no measurable difference: nikic.github.com/2012/01/09/…Verne
Yes, in earlier versions of PHP (<= 4.3) there was a trivial but measurable difference (on the order of microseconds). Since 4.4 the parser works differently which basically sped up double quotes to be the same for the vast majority of cases. Either way, the difference is so minute that it's a micro-optimization to even consider the difference...Verne
You need to use ' with php as html has " marks everywhere.Ganda
W
45

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.

Winters answered 17/8, 2008 at 15:10 Comment(5)
Surely you can't beat a real life test. But this artificial frankenstein has nothing in common with the real life conditions.Cubage
Those skeptics trying to reproduce these results (like me ;-) on PHP5+ change the microtime() calls to microtime(true) - you want the time as a float, not as some sort of weird string.Gujarat
Added Method4() for string processing. And I think PHP processing got more faster now. @AdamWrightThromboplastin
Hello. Your comparison assumes that there is but a single instance of the variable within a string. Please see https://mcmap.net/q/102847/-how-to-add-php-variable-in-url-name-not-in-url-link-closedCallas
This confuses me: "about 66% of the speed", ain't that "about 66% of the time"? I thought concatenation is faster?Massarelli
J
25

Live benchmarks:

http://phpbench.com/

There is actually a subtle difference when concatenating variables with single vs double quotes.

Jola answered 27/1, 2009 at 4:8 Comment(2)
I think that it depends on hardware configuration and compiled php.Rubstone
I didn't know you could use a comma in echo, instead of dot.Hesitate
N
18

@Adam's test used

"these are " . $foo

note that the following is even faster:

'these are ' . $foo;

this is due to the fact, that a double quoted "string" gets evaluated, where a single quoted 'string' is just taken as is...

Nernst answered 17/8, 2008 at 15:44 Comment(1)
I've just done some quick testing and there's not much of a saving between these two - certainly nowhere near as much as changing interpolation to concatenation - but single quotes are faster.Carrollcarronade
P
13

Don't get too caught up on trying to optimize string operations in PHP. Concatenation vs. interpolation is meaningless (in real world performance) if your database queries are poorly written or you aren't using any kind of caching scheme. Write your string operations in such a way that debugging your code later will be easy, the performance differences are negligible.

@uberfuzzy Assuming this is just a question about language minutia, I suppose it's fine. I'm just trying to add to the conversation that comparing performance between single-quote, double-quote and heredoc in real world applications in meaningless when compared to the real performance sinks, such as poor database queries.

Plagio answered 19/8, 2008 at 13:12 Comment(0)
T
10

Any differences in execution time are completely negligible.

Please see

Don't waste time on micro-optimizations like this. Use a profiler to measure the performance of your application in a real world scenario and then optimize where it is really needed. Optimising a single sloppy DB query is likely to make a bigger performance improvement than applying micro-optimisations all over your code.

Triphylite answered 19/6, 2012 at 18:27 Comment(1)
Amen! I've noticed that in different language communities different things are valued, and the performance of single quotes seems to be a sacred cow of the PHP world.Surplusage
R
4

there is a difference when concatenating variables... and what you are doing with the result... and if what you are doing is dumping it to output, is or isn't output buffering on.

also, what is the memory situation of the server? typically memory management on a higher level platform is worse than that at lower platforms...

$a = 'parse' . $this; 

is managing memory at the user code platform level...

$a = "parse $this";

is managing memory at the php system code platform level...

so these benchmarks as related to CPU don't tell the full story.

running the benchmark 1000 times vs running the benchmark 1000 times on a server that is attempting to run that same simulation 1000 times concurrently... you might get drastically different results depending on the scope of the application.

Rehnberg answered 16/9, 2009 at 21:25 Comment(1)
Plus 1 for " typically memory management on a higher level platform is worse than that at lower platforms... "Sama
P
3

I seem to remember that the developer of the forum software, Vanilla replaced all the double quotes in his code with single quotes and noticed a reasonable amount of performance increase.

I can't seem to track down a link to the discussion at the moment though.

Piegari answered 27/1, 2009 at 3:22 Comment(0)
S
2

Just to add something else to the mix, if you are using a variable inside a double quoted string syntax:

$foo = "hello {$bar}";

is faster than

$foo = "hello $bar";

and both of these are faster than

$foo = 'hello' . $bar; 
Sarrusophone answered 12/10, 2012 at 10:1 Comment(0)
L
1

Double quotes can be much slower. I read from several places that that it is better to do this

'parse me '.$i.' times'

than

"parse me $i times"

Although I'd say the second one gave you more readable code.

Liege answered 27/1, 2009 at 4:36 Comment(5)
Uh, no: in my experience working with other people's code, the first one is much more readable.Ware
@Ware just get yourself good editor with syntax highlighting, dude.Cubage
I do use a syntax-highlighting editor. The highlighting works much better with the first variant.Ware
PhpStorm editor works good with highlighting on both examples.Rubstone
I read from several places - What places? Please provide documentation.Chimene
I
0

Practically there is no difference at all! See the timings: http://micro-optimization.com/single-vs-double-quotes

Immoralist answered 27/5, 2011 at 22:10 Comment(0)
S
0

It should be noted that, when using a modified version of the example by Adam Wright with 3 variables, the results are reversed and the first two functions are actually faster, consistently. This is with PHP 7.1 on CLI:

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';
    $bar = 'other words';
    $bas = 3;
    for ($i = 0; $i < 10000; $i++)
         $t = "these are $foo, $bar and $bas";
}

function Method2()
{
    $foo = 'some words';
    $bar = 'other words';
    $bas = 3;
    for ($i = 0; $i < 10000; $i++)
         $t = "these are {$foo}, {$bar} and {$bas}";
}

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

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

I've also tried with '3' instead of just the integer 3, but I get the same kind of results.

With $bas = 3:

0.0016254
0.0015719
0.0019806

With $bas = '3':

0.0016495
0.0015608
0.0022755

It should be noted that these results vary highly (I get variations of about 300%), but the averages seem relatively steady and almost (9 out of 10 cases) always show a faster execution for the 2 first methods, with Method 2 always being slightly faster than method 1.

In conclusion: what is true for 1 single operation (be it interpolation or concatenation) is not always true for combined operations.

Somatology answered 26/4, 2017 at 4:56 Comment(1)
I wonder how much of this is from the flipping, and how much of it was optimizations in php7. The original question was specific to mention a context of php5.Sasha
T
0

Yes, originally this is about PHP5, however in few months arrive PHP8 and today the best option tested over my PHP 7.4.5 is use PHP - Nowdoc (tested over WIN 10 + Apache and CentOs 7 + Apache):

function Method6(){
    $k1 = 'AAA';
    for($i = 0; $i < 10000; $i ++)$t = <<<'EOF'
K1= 
EOF
.$k1.
<<<'EOF'
K2=
EOF
.$k1;
    }

here the method #5 (using Heredoc to concatenat):

function Method5(){
    $k1 = 'AAA';
    for($i = 0; $i < 10000; $i ++)$t = <<<EOF
K1= $k1
EOF
.<<<EOF
K2=$k1 
EOF;
    }

the methods 1 to 4 is in beginning of this post

In all my tests the "winner" is method #6 (Newdoc), no't very easy to read, but very fast in CPU and ever using the function function timeFunc($function) by @Adam Wright.

Toddler answered 19/7, 2020 at 22:8 Comment(0)
F
0

I have tested php 7.4 and php 5.4 with following test cases, It was little still confusing to me.

<?php
$start_time = microtime(true);
$result = "";
for ($i = 0; $i < 700000; $i++) {
    $result .= "THE STRING APPENDED IS " . $i;
    // AND $result .= 'THE STRING APPENDED IS ' . $i;
    // AND $result .= "THE STRING APPENDED IS $i";
}
echo $result;
$end_time = microtime(true);
echo "<br><br>";
echo ($end_time - $start_time) . " Seconds";

PHP 7.4 Outputs

 1. "THE STRING APPENDED IS " . $i = 0.16744208335876
 2. 'THE STRING APPENDED IS ' . $i = 0.16724419593811
 3. "THE STRING APPENDED IS $i" = 0.16815495491028

PHP 5.3 Outputs

 1. "THE STRING APPENDED IS " . $i = 0.27664494514465
 2. 'THE STRING APPENDED IS ' . $i = 0.27818703651428
 3. "THE STRING APPENDED IS $i" = 0.28839707374573

I have tested so many times, In php 7.4 it seems to be all 3 test cases got same result many times but still concatenation have little bittle advantage in performance.

Fulminate answered 1/7, 2021 at 8:3 Comment(0)
T
0

Based on @adam-wright answer, I wanted to know if speed difference happens without no concataining / no vars in a string.

== My questions...

  • is $array['key'] call or set faster than $array["key"] !?
  • is $var = "some text"; slower than $var = 'some text'; ?

== My tests with new vars every time to avoid use same memory address :

function getArrDblQuote() { 
    $start1 = microtime(true);
    $array1 = array("key" => "value");
    for ($i = 0; $i < 10000000; $i++)
        $t1 = $array1["key"];
    echo microtime(true) - $start1;
}
function getArrSplQuote() {
    $start2 = microtime(true);
    $array2 = array('key' => 'value');
    for ($j = 0; $j < 10000000; $j++)
        $t2 = $array2['key'];
    echo microtime(true) - $start2;
}

function setArrDblQuote() { 
    $start3 = microtime(true);
    for ($k = 0; $k < 10000000; $k++)
        $array3 = array("key" => "value");
    echo microtime(true) - $start3;
}
function setArrSplQuote() {
    $start4 = microtime(true);
    for ($l = 0; $l < 10000000; $l++)
        $array4 = array('key' => 'value');
    echo microtime(true) - $start4;
}

function setStrDblQuote() { 
    $start5 = microtime(true);
    for ($m = 0; $m < 10000000; $m++)
        $var1 = "value";
    echo microtime(true) - $start5;
}
function setStrSplQuote() {
    $start6 = microtime(true);
    for ($n = 0; $n < 10000000; $n++)
        $var2 = 'value';
    echo microtime(true) - $start6;
}

print getArrDblQuote() . "\n<br>";
print getArrSplQuote() . "\n<br>";
print setArrDblQuote() . "\n<br>";
print setArrSplQuote() . "\n<br>";
print setStrDblQuote() . "\n<br>";
print setStrSplQuote() . "\n<br>";

== My Results :

array get double quote 2.1978828907013

array get single quote 2.0163490772247

array set double quote 1.9173440933228

array get single quote 1.4982950687408

var set double quote 1.485809803009

var set single quote 1.3026781082153

== My conclusion !

So, result is that difference is not very significant. However, on a big project, I think it can make the difference !

Thanatos answered 15/7, 2021 at 9:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.