Вопрос

Possible Duplicate:
Is there a performance benefit single quote vs double quote in php?

I am wondering if PHP code takes a performance hit when using "s when defining strings containing no variables, compared to ' where the extra parsing is not performed.

For example, PHP will try to parse variables inside strings defined by " but not '.

$myString = "Greetings earthlings!";
echo '$myString'; //literally outputs the string '$myString'
echo "$myString"; //literally outputs the string "Greetings earthlings"

So my question is, all this time I've been writing code like this:

echo "Greetings earthlings";

Have I been wasting cycles? Or is PHP smart/optimized enough to know I really meant:

echo 'Greetings earthlings';

?

Это было полезно?

Решение

A bit of work with VLD tells me that both programs compile to identical bytecode (using PHP 5.3):

line     # *  op                           fetch          ext  return  operands
---------------------------------------------------------------------------------
   2     0  >   ECHO                                                     'Hello+world'
   3     1    > RETURN                                                   1

Conclusion: There's absolutely no difference in modern versions of PHP. None whatsoever. Use whatever feels best to you.


There is, however, a difference between echo "Hello $world":

compiled vars:  !0 = $world
line     # *  op                           fetch          ext  return  operands
---------------------------------------------------------------------------------
   1     0  >   ADD_STRING                                       ~0      'Hello+'
         1      ADD_VAR                                          ~0      ~0, !0
         2      ECHO                                                     ~0
         3    > RETURN                                                   null

And echo "Hello " . $world:

compiled vars:  !0 = $world
line     # *  op                           fetch          ext  return  operands
---------------------------------------------------------------------------------
   1     0  >   CONCAT                                           ~0      'Hello+', !0
         1      ECHO                                                     ~0
         2    > RETURN                                                   null

I'd hesitate to call that significant, though. The actual real-world difference in performance is, in all probability, trivial.

Другие советы

It is possible to run benchmarks to see. I did for PHP 4 and discovered that doing string concatenation was much faster (an order of magnitude? I don't remember exactly) than embedded variables. By comparison, plain strings in double quotes were only very slightly faster than single quotes.

But that was for PHP 4. I ran the same tests later for PHP 5 and the difference in performance is pretty much negligible.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top