i understand about the difference between single and double quotes, but are there any benefits of using single quotes other than the speed? and is this speed difference worth while?
also, why do double quotes slow the process down? :o

thanks

    The speed difference is quite small and probably not worth worrying about in most cases. That being said, double quotes are a bit slower mainly because the parser has to look for variables within the string, and replace them with their values when it finds them. (It also has to do a similar replacement for special escape sequences such as "\n" for a newline.)

    So, if you do the following, the single-quoted version will be faster (though maybe only by a micro-second or two):

    $text = 'This is a test.';  // a bit faster than:
    $text = "This is a test.";
    

    But, if variables are involved, I'm not sure which would be faster:

    $var = 'test';
    // which is faster? (I don't know.):
    $text = "This is a $var.";
    $text = 'This is a'.$var.'.';
    $trext = sprintf('This is a %s.', $var);
    

      Actually, empirical tests done by a couple of us here at phpbuilder suggest that for the first example, the speed difference really is negligible. For the second example, variable interpolation ("This is a $var.") is slower than concatenation ('This is a'.$var.'.'). The third example, sprintf() appears to be in between, though not much faster than variable interpolation (which makes sense to me, since the format string also has to be parsed for the various format specifiers).

      Still, the speed difference does not usually matter.

        Consider the case of defining a large html string. Tons of double-quotes inside of it. Much easier to wrap the whole thing in single-quotes and concatenate any vars in than to change all the double-quotes to singles or escape all the doubles.

        As a rule, I use double-quotes in most cases and singles-quotes whenever I want more than a couple double-quotes within the string.

          Tyree wrote:

          Consider the case of defining a large html string. Tons of double-quotes inside of it. Much easier to wrap the whole thing in single-quotes and concatenate any vars in than to change all the double-quotes to singles or escape all the doubles....

          Or, use the heredoc method of quoting and you don't have to escape any quotes nor concatenate variables. 🙂

          $var = 'test';
          $longstring = <<<END
          NogDog said, "This is a $var. It is only a $var."
          He could also have quoted it as, 'This is a $var. It is only a $var.'
          If it's not clear where a variable name ends/begins, use the
          "complex" method of variable notation, such as, "{$var}ing one, two, three."
          END;
          
          echo $longstring;
          

            OOOOOO...man, I love this site.

            NogDog...you're on my Christmas card list! 😉

              Write a Reply...