Optimizing PHP string concatenation

Hello there,

This post is not really a question, but it could be useful to share some coding tips.

Here is the one I'de like to share with you. I'm gonna show you 4 examples to do the same thing, but only the last one will be the best.

$foo = 'John SMITH';

echo
"Hello $foo, welcome on my website.";

echo
"Hello " . $foo . " welcome on my website.";

echo
'Hello ' . $foo . ' welcome on my website.';

echo
'Hello ', $foo , ' welcome on my website.';

I'm sure you all know that echo '$foo' won't work, but still, I'm pretty sure that you use double quote to display a simple information. THIS IS BAD.

Well let's begin : The first one is bad (as well as the second) because using double quote forces php to scan the string to look for a substitution to be done (I mean a variable).

The second one is a little better, since php has no replacement to do.

The third one, is better because of simple quote, so that the language knows he can just send the text without processing, but the "bad" thing is the use of concatenation (dot operator, like in the second example).

The last one uses simple quote, and the coma operator. Why is this solution better?

Well, what happens when Using the third solution?

php creates a string, containing "Hello ", then it has to enlarge it, to put the content of foo variable ("John SMITH"), and then, enlarge it again to put " Welcome on my website." sentence. Then, echo can use this, to ... echo it :)

Whereas in the 4th one, the only thing to do for echo is to send "Hello ", then $foo's content, then " Welcome on my website." to the output, and that is all! Because echo just has to send the text, without creating a string that will have to be enlarged to contain the whole texte (that would have been concate, which has to be grown (because of concatenation) and then displayed.

I'll try to find back some benchmarks and put them here.

Fell free to comment or react, and excuse my english, this is not my mother thong.


0 comments: