Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Speed difference in using inline strings vs concatenation in php5?

(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?

like image 907
Uberfuzzy Avatar asked Aug 17 '08 13:08

Uberfuzzy


People also ask

Is string interpolation faster than concatenation?

String concatenation is a little faster for a very small number of arguments, but requires more memory. After 20+ arguments concat is better by time and memory.

Is string concatenation slow in Java?

Let me say the reason that string concatenation is slow is because strings are immutable. This means every time you write "+=", a new String is created. This means the way you build up your string is in the worst case, O(n2).

What is the most efficient way to concatenate many strings together?

Concatenate Many Strings using the Join As shown above, using the join() method is more efficient when there are many strings.

What is the difference between string interpolation and string concatenation?

You can think of string concatenation as gluing strings together. And, you can think of string interpolation without strings as injecting strings inside of other strings.


1 Answers

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

like image 185
5 revs, 3 users 71% Avatar answered Sep 21 '22 11:09

5 revs, 3 users 71%