Is there a performance gain in using single quotes vs double quotes in ruby?

$ ruby -v
ruby 1.9.3p0 (2011-10-30 revision 33570) [x86_64-darwin11.0.0]

$ cat benchmark_quotes.rb
# As of Ruby 1.9 Benchmark must be required
require 'benchmark'

n = 1000000
Benchmark.bm(15) do |x|
  x.report("assign single") { n.times do; c = 'a string'; end}
  x.report("assign double") { n.times do; c = "a string"; end}
  x.report("concat single") { n.times do; 'a string ' + 'b string'; end}
  x.report("concat double") { n.times do; "a string " + "b string"; end}
end

$ ruby benchmark_quotes.rb 

                      user     system      total        real
assign single     0.110000   0.000000   0.110000 (  0.116867)
assign double     0.120000   0.000000   0.120000 (  0.116761)
concat single     0.280000   0.000000   0.280000 (  0.276964)
concat double     0.270000   0.000000   0.270000 (  0.278146)

Note: I've updated this to make it work with newer Ruby versions, and cleaned up the header, and run the benchmark on a faster system.

This answer omits some key points. See especially these other answers concerning interpolation and the reason there is no significant difference in performance when using single vs. double quotes.


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.