Summary: no speed difference; this great collaborative Ruby style guide recommends being consistent. I now use 'string'
unless interpolation is needed (option A in the guide) and like it, but you will typically see more code with "string"
.
Details:
Theoretically, it can make a difference when your code is parsed, but not only should you not care about parse time in general (negligible compared to execution time), you won’t be able to find a significant difference in this case.
The important thing is that when is gets executed it will be exactly the same.
Benchmarking this only shows a lack of understanding of how Ruby works. In both cases, the strings will get parsed to a tSTRING_CONTENT
(see the source in parse.y
). In other words, the CPU will go through the exact same operations when creating 'string'
or "string"
. The exact same bits will flip the exact same way. Benchmarking this will only show differences that are not significant and due to other factors (GC kicking in, etc.); remember, there can’t be any difference in this case! Micro benchmarks like these are difficult to get right. See my gem fruity
for a decent tool for this.
Note that if there is interpolation of the form "...#{...}..."
, this gets parsed to a tSTRING_DBEG
, a bunch of tSTRING_DVAR
for the each expression in #{...}
and a final tSTRING_DEND
. That’s only if there is interpolation, though, which is not what the OP is about.
I used to suggest you use double quotes everywhere (makes it easier to actually add that #{some_var}
later on), but I now use single quotes unless I need interpolation, \n
, etc… I like it visually and it’s slightly more explicit, since there’s no need to parse the string to see if it contains any expression.