phpoptimizationphp-opcode

PHP String literals and compiler optimization


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';

?


Solution

  • 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.