Musings of an 8-bit Vet

A Student Coders Tech Diary

Make Mine a Single: On the Use of Quotation Marks

Here are two lines of Ruby code:

1
2
puts 'Have a nice day!'
puts "Have a nice day!"

They both print the same string to the display. The first uses ‘single quotes’, the second uses “double quotes”. Now, any new Rubyist quickly learns that you use single quotes for simple or static strings, and double quotes for more complicated strings, with special characters, etc. You also use double quotes for so-called “interpolated strings”, where you want to be able to print a variable or other derived value in the string, e.g.

1
puts "Have a nice day, #{person_name}"

So if double quotes will perform the same function as single quotes, why not just use them all the time?

When I posed this question in class the other day it was suggested that whenever the Ruby interpreter sees single quotes it just prints the string, and doesn’t bother to check if there is anything possibly going on in between the ‘’’s. But when Ruby sees double quotes, it has to check each character to see if there is any interpolation required. This is time consuming, and computationally costly. If you are working with thousands of lines of code it can really add up.

So I wrote a quick benchmark to check just how costly this really is, the total time taken is displayed after real:

1
2
3
4
5
6
7
8
9
10
time ruby quote_test.rb   # puts 'Hello there!' * 1,000,000

real  0m5.130s
user  0m0.081s
sys 0m0.150s

time ruby quotes_test.rb  # puts "Hello there!" * 1,000,000
real  0m5.076s
user  0m0.081s
sys 0m0.152s

Huh? Turns out a million puts is actually slightly faster with double quotes. Maybe I need to give Ruby some more to do:

1
2
3
4
5
6
7
8
9
time ruby quote_test.rb   # puts 'Hello there!' * 3,000,000
real  0m15.246s
user  0m0.087s
sys 0m0.357s

time ruby quotes_test.rb  # puts "Hello there!" * 3,000,000
real  0m15.170s
user  0m0.088s
sys 0m0.347s

WTF? Double quotes is still slightly faster. Guess we need to dig a little deeper.

Turns out there is big discussion of this on Stack Overflow, click the link to read all about it.

The short version is this, Ruby doesn’t just pass over single quoted strings when it evaluates. It has to look at every character to render the string in memory, regardless of single or double quotes, even with interpolation. After some pretty extensive bench-marking there is no real cost to using double quotes, and it is often slightly faster.

I suspect that the real reason we use single quotes is one of style. It can’t be for code efficiency, and if you later need to update a string to use interpolation, you would also have to change the single quotes to double quotes.

I’m all about style, so make mine a single!

(But I reserve the right to change my mind later…)