Articles

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'

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

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 comment