Monday, September 19, 2011

QOTD "Faster! Faster!"

I recently advised our team to used single quotes instead of double quotes, unless they obviously need interpolation in the strings.

Of course, I immediately got a nice reply about about a benchmark to compare the two use cases. I did not even look it up before making the recommendation. I try not to let facts cloud my opinions.

So there is the benchmark, as extolled on StackOverflow:

$ ruby -v
ruby 1.8.7 (2008-08-11 patchlevel 72) [i686-darwin9.6.2]
$ cat benchmark_quotes.rb
require 'benchmark'
n = 1000000 do |x|"assign single") { n.times do; c = 'a string'; end}"assign double") { n.times do; c = "a string"; end}"assing interp") { n.times do; c = "a string #{'b string'}"; end}"concat single") { n.times do; 'a string ' + 'b string'; end}"concat double") { n.times do; "a string " + "b string"; end}

$ ruby -w benchmark_quotes.rb 
      user     system      total        real
assign single  2.600000   1.060000   3.660000 (  3.720909)
assign double  2.590000   1.050000   3.640000 (  3.675082)
assing interp  2.620000   1.050000   3.670000 (  3.704218)
concat single  3.760000   1.080000   4.840000 (  4.888394)
concat double  3.700000   1.070000   4.770000 (  4.818794)

So doubles on the whole are just fine to use all the time. In fact, single quotes are a tad slower in basic use. Who knew.

To quote, "Just because my opinion has changed, does not mean the fact that I'm right has."*

*See what I did there?


  1. Answer: &


    Double quotes for the general case is perfectly fine. If however you're using massive static strings in your script single qoutes tend to be more efficient.