codahale.com٭blog

Coda Hale lives in Berkeley, CA, where he writes about Ruby on Rails, usability, web design and development, and the occasional bit about bicycles.

Ever wonder which is the fastest way to concatenate strings in Ruby?

No? Too bad!

From this:


require 'benchmark'
Benchmark.bm(20) do |x|
  x.report ('<<') do
    1_000_000.times do
      one = 'one'
      two = 'two'
      three = 'three'
      y = one << two << three
    end
  end
  x.report('+') do
    1_000_000.times do
      one = 'one'
      two = 'two'
      three = 'three'
      y = one + two + three
    end
  end
  x.report('#{one}#{two}#{three}') do
    1_000_000.times do
      one = 'one'
      two = 'two'
      three = 'three'
      y = "#{one}#{two}#{three}"
    end
  end
  x.report('one#{two}#{three}') do
    1_000_000.times do
      two = 'two'
      three = 'three'
      y = "one#{two}#{three}"
    end
  end
  x.report('onetwo#{three}') do
    1_000_000.times do
      three = 'three'
      y = "onetwo#{three}"
    end
  end
end

Comes this:


                           user     system      total        real
<<                     4.580000   0.000000   4.580000 (  4.579776)
+                      5.720000   0.000000   5.720000 (  5.815782)
#{one}#{two}#{three}   5.180000   0.000000   5.180000 (  5.185434)
one#{two}#{three}      3.920000   0.000000   3.920000 (  3.917942)
onetwo#{three}         2.610000   0.000000   2.610000 (  2.617674)

Thus proving a two things:

  1. Use << for concatenation. It doesn’t make an intermediate copy, unlike +.
  2. If you need to place a string variable inside a chunk of static text, it’s far faster to use interpreted string literals than to concatenate string variables.

Yup.

5 comments »