name = "Bob"
str1 = "Hello #{name}!"
str2 = 'Hello #{name}!'
puts str1 # Hello Bob!
puts str2 # Hello #{name}!
require 'benchmark'
Benchmark.bm do |b|
b.report("with single") { 100000.times do ; name = "Bob"; str1 = 'Hello #{name}!'; end }
b.report("with double") { 100000.times do ; name = "Bob"; str2 = "Hello #{name}!"; end }
end
user system total real
with single 0.300000 0.020000 0.320000 ( 0.358628)
with double 0.500000 0.040000 0.540000 ( 0.573899)
require 'benchmark'
n = 10000000
Benchmark.bmbm do |x|
x.report("Single Quote") { n.times {"Hello"} }
x.report("Double Quote") { n.times {'Hello'} }
end
christopher@deb-server:~/repository$ ruby1.9 thing.rb
Rehearsal ————————————————
Single Quote 4.730000 0.000000 4.730000 ( 4.724137)
Double Quote 4.800000 0.000000 4.800000 ( 4.796206)
————————————— total: 9.530000sec
user system total real
Single Quote 4.730000 0.010000 4.740000 ( 4.732299)
Double Quote 4.810000 0.000000 4.810000 ( 4.806372)
christopher@deb-server:~/repository$
1. Benchmark code! Ruby makes it very easy to profile and benchmark code. Often times you'll find surprising results.
2. Use ! operations. I alluded to it above.
hash.merge is more expensive than hash.merge!. str.sub is more expensive than str.sub!. That can be said for virtual all of the destructive methods. That's because of data being duplicated. Depending on the data (especially with big strings) this can make a noticeable difference. Don't write your code around this—But if you find yourself able to use either–Go with ! methods.
3. Native str subs are your friend.
4. Avoid needless lookups
This especially rings true in 1.8x but look at this.
5. Avoid reinventing the wheel
When available use the built-in classes and methods. This isn't just to lower man hours—They're optimized and often/always written in C rather than pure ruby. This makes a *great* deal of difference. Even sometimes piggy backing your algorithms with the standard libraries is a better idea than rewriting something to get additional functionality in pure ruby. (Like any of the string parsing methods, for example.)