PHP Single vs. Double Quotes

For a long time, I’ve been a proponent of using single-quotes as opposed to double-quotes when assigning string literals (strings containing no variables) to a variable (eg: $var = ’string’; VS $var = “string”).

I just did some research to find out how much (if any) impact using single-vs-double quotes had on performance. I took the code from this blog post: http://spindrop.us/2007/03/03/php-double-versus-single-quotes/ modified the MAX constant to 8,000,000 and then ran the test on our Nexcess server. The results were fairly consistent:

Time 1: 5.9485120773315 ($c = “test ” . $i; )
Time 2: 7.0326972007751 ($c = “test $i”; )
Time 3: 5.9164550304413 ($c = ‘test ‘ . $i; )

It’s clear that embedding variables in strings is less efficient, but the difference between normal single-vs-double quotes is negligible (at least on our server configuration with this test).

Despite the lack of clear performance benefits, I still think it best practice to use single-quotes when using string literals, as it denotes that a string doesn’t contain any variables. One benefit of this is that when skimming code, you can more quickly process which variables are string literals vs strings with embedded variables.

The Zend Framework Coding Standard also recommends this practice: http://framework.zend.com/manual/en/coding-standard.coding-style.html

This entry was posted on Sunday, February 7th, 2010 at 12:21 am and is filed under PHP. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

One Response to “PHP Single vs. Double Quotes”

  1. cam Says:

    February 10th, 2010 at 5:03 am

    Most programming languages don’t give you that much latitude when it comes to quotes. Of course, the guys that brought us PHP are kind of on the dyslexic side when it comes to a lot of things. The name itself for example. How exactly to you get PHP from Hypertext Pre-Processor? Shouldn’t it be HPP?

    And what about the nastiness that is a PHP foreach array loop?


    $arr = array(1, 2, 3, 4);
    foreach ($arr as $value) {
    // do something
    }

    Any normal human being would read this as:

    for each array as value do something

    Wouldn’t it make far more sense to do something like:


    $arr = array(1, 2, 3, 4);
    foreach ($value in $arr) {
    // do something
    }

    for each value in array do something

    Of course, those are just my thoughts on it – YMMV.

Comment Form

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Call us at 417-597-4769, email us at sales@classyllama.com, or use this form to contact us:

  1. (required)
  2. (required)
 

cforms contact form by delicious:days