Single Quotes or Double Quotes?

In Ruby on July 25, 2008 by Matt Grande Tagged:

Josh Susser recently had an interesting article about Symbols. I had noticed that in many places where I thought I should be able to use symbols, I had to use strings (the routes file comes to mind).

Reading that post got me thinking about the differences between ‘strings’ and “strings.” I knew that “strings” allowed you to do mid-string insertions:

puts "Your variable is #{my_var}."

On the other hand, with ‘strings’ you had to use plus signs:

'Your variable is ' + my_var + '.'

I began to wonder if one was faster than the other. I had been told that single quotes were faster, but I had no idea if this was true, or by how much. I decided to run some benchmarks to see how quickly a string could be saved using the different methods.

require 'benchmark'
test_variable = 'a string' do |x|"Single Quotes, no insertion") {
    10000.times do
      str = 'Text without insertion'
  }"Double Quotes, no insertion") {
    10000.times do
      str = "Text without insertion"
  }"Single Quotes, with insertion") {
    10000.times do
      str = 'Inserting ' + test_variable + ' into a string.'
  }"Double Quotes, with insertion") {
    10000.times do
      str = "Inserting #{test_variable} into a string."

It turns out that single quotes are, in fact, slower than double quotes. Here’s my results:

                               user       system     total    real
Single Quotes, no insertion    0.000000   0.000000   0.000000 (  0.003485)
Double Quotes, no insertion    0.010000   0.000000   0.010000 (  0.002694)
Single Quotes, with insertion  0.010000   0.000000   0.010000 (  0.011286)
Double Quotes, with insertion  0.010000   0.000000   0.010000 (  0.009462)

Now keep in mind, my benchmarks were based on saving 10,000 strings. That means for every string using single quotes you have is wasting over 0.00000018 seconds. In other words, you would need to convert about 5.4 million single-quoted strings to double-quoted string to save one second of running time.

Happy coding!


One Response to “Single Quotes or Double Quotes?”

  1. well, I don’t know about you, but I process 5.4 million strings at least twice a second. So I guess that means that if I apply your theory, not only would I save time, I might be able to gain time and somehow create a time machine.

    Thanks for these benchmarks. This has been something I’ve wondered about for a while.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: