Pergunta

As far as I can see (browsing popular PHP code in GitHub) there are many people not using string interpolation:

$loader->load($config['resource'].'.xml');

Versus:

$loader->load("{$config['resource']}.xml");

Is there any reason (i.e. performances) for not using string interpolation?

Foi útil?

Solução

No, there is no reason not to be using string interpolation in PHP.

While there are tiny differences in how PHP handles string interpolation and concatenation internally, those differences are so small that they are barely measurable in practice, and should therefore be left to PHP to handle.

If or when you see benchmarks, for working with strings in PHP, the thing to look for is usually the iteration count. In order to get measurable results you need to set n to some highly exaggerated value, which never occurs in the real world.

To wrap up, optimizing how you work with strings in PHP does not make much sense. Instead, you should focus on problems that actually have a noticeable effect on the performance of your website; caching, database stuff and, especially, the front end.

Outras dicas

Is there any reason (i.e. performances) for not using string interpolation?

Not performance, definitely.

The only reasons are readability and usability. I.e. in the given example second line have obstacles in the form of curly braces, which are either useless and makes the code harder to read. Why use them then?

However, if it was

"$somevar.xml"

it would be just a matter of taste to write it this way or with concatenation

$somevar.".xml"

Most of the time this is a matter of taste only. And I'm not sure that you really observed an overall preference here, but I already wrote that in a comment.

As far as performance is concerned:

Interpolation becomes more efficient the more is interpolated. [ref]

But if performance is concerned can not be easily said. This needs concrete code and then concrete performance measurements of that code. Because in most of the cases you won't notice a difference.

No, it is not but some people think that it is bad code. But I do not agree with that argument. It think the code looks a lot of clearer and it is one thing which I love a lot in PHP.

At the moment, I am not able to find a benchmark test but I can remember the results. The results are nearly equals (+/- 0.0001 secound by 100 interactions).

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top