The coding standards need to be updated with a section about strings.
Constant strings should not be contained by double quotes. Here are some reasons why.
1. Performance: every string surrounded by double quotes ("a sample string") has to be parsed by php to see if it contains any special characters, or variables. There are so many of these strings in the drupal source there must be some performance penalty.
2. Code Readability: when ever a coder sees a string in double quotes he/she has to examine the string to see if there is any variable replacement, or special characters in the string. It is much easier to read code with single quoted strings.
i.e.
Double quotes:
$url = "<a href=\"filename/$somevar?opt=$someothervar\">$link_title</a>";
Single quotes:
$url = '<a href="/filename/' . $somevar . '?opt=' . $someothervar . '">' . $link_title . '</a>';
With the single quoted string it is much easier to se where the variables are used, and php does not have to any extra parsing on the string.
Comments
Comment #1
dries commentedI'm OK with using (or starting to use) single qoutes for constant strings. We would also have to update our
script/code-style.plscript though.It is acceptable to use double quotes when the string has variables; after all, any editor with decent syntax highlighting will highlight the variables embedded in double-quoted strings.
Comment #2
gábor hojtsyAs far as I know your first example will be faster and will use less memory than the second. Concatenation uses much more memory then string parsing. There are dozens of benchmarks out there, see http://www.blueshoes.org/phpBench.php for example (there is a simple single/double quote benchmark there). It would be interesting to see benchmarks on concatenation/single qoutes, variable replacement/double quotes :) My guess is that the second will be faster (and it is more readable IMHO :)
Comment #3
CodeMonkeyX commentedYeah the actual examples I posted were for readability not performance. It is hard to see becuase all my paragraphs got squashed together. But I still think that a few concats would be faster than running a search like function on a string.
The performance one was just for regular constant strings.
Comment #4
gábor hojtsyAs the benchmarks referenced in my post show, there is *no performance difference* between "some text" and 'some text', so performance reasons should not be cited. Or do a benchmark, and show that :) Building development on wrong assumptions just makes too much unneded work, which is better spent on doing valuable development...
Comment #5
moshe weitzman commentedComment #6
Uwe Hermann commentedDrupal 4.2.x is pretty old now...
Comment #7
Crell commentedThis issue is pretty old now... :-)
Comment #8
(not verified) commented