Here are two lines of Ruby code:
1 2 |
|
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
|
|
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 |
|
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 |
|
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…)