Ruby, Strings and Speed
 
 
John_2 John Fitzpatrick
November 20, 2012
John_2 John Fitzpatrick
November 20, 2012

Strings, in Ruby, can be delimited using either double quotes (") or single quotes ('). The difference being that Strings delimited by double quotes are interpreted, while Strings with single quotes are not.

Interpretation of Strings allows us to do some run-time substitution of values, which can be handy. Consider the following code block:

names = ['John','Jim']
names.each do |name|
   puts "My name is #{name}"
end

If we run that code, we get:

My name is John
My name is Jim

That interpretation comes at a cost however. If we assign a String that we could delimit with single quotes using double quotes we're taking an unnecessary performance hit. Try the following code:

puts Time.now.to_f
[1..1000000].each do
        test = "This is a test string"
end
puts Time.now.to_f
[1..1000000].each do
        test = 'This is a test string'
end
puts Time.now.to_f

If we run that code, we get something like the following:

1353430303.321
1353430303.527
1353430303.529

What we're doing here is taking an initial timestamp, doing a double-quoted assignment a million times, followed by a timestamp, followed by a single-quote assignment a million times, followed by another timestamp. The decimal portion of the timestamp is in milliseconds. The verdict: single-quoted assignment is two orders of magnitude faster than double-quoted assignment (2 milliseconds versus 206 milliseconds). All this may not sound like much, but done consistently throughout your code base over the life of an application these tiny fractions of a second will add up.

Disclaimer: These results were produced on a 2.4 Ghz MacBook Pro using JRuby 1.6.4 on Java 1.6. Your mileage may vary.

 
 
 

Newsletter Sign-Up

Be the first to find out about the goings on at the Lab!

Email: