Concatenation vs Interpolation

Looks like one of the PHP’s eternal discussions could be over, the interpolation of variables in strings versus the concatenation of its values.

I’ve always been a fan of concatenation, it’s more readable and looked more natural in the code and several days ago while discussing some changes in the way we create code at Trovit we had this classic confrontation.

We looked for this in the Internet a little bit and we found a comment in the PHP forums with some benchmark info about this particular subject.

This image shows that the code used for this benchmark took less (half of the time to be exact) when using concatenation with single quotes to send the code to the user, but the strange thing is when sending the same code to the output buffer the interpolation is faster… that’s hard to believe.

In this stackoverflow post all the commenters agree, concatenation with single quotes is way faster than other options (concatenation with double quotes is like the worst of both worlds).

So if you’re one of those using:

echo "Hello, {$user_name}" ;

instead of using:

echo 'Hello, ' . $user_name ;

you should switch now.

By the way, if you want to get more optimization ideas, this presentation by Ilia Alshanetsky is really good.

Thanks Gonzalo for the tips.

Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos necesarios están marcados *