codahale.com٭blog

This is my old blog. My current writing is here: codahale.com

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 Responses to “Ever wonder which is the fastest way to concatenate strings in Ruby?”

  1. Peter Says:

    How bizarre. I understand why “Joe ” + “and ” + “Monkey” might require intermediate copies, but I would expect Ruby to be smart enough to translate “Joe and ” + “Monkey” into “Joe and “

  2. Pensando en voz alta » Blog Archive » Optimiza la concatenacion de strings en Ruby Says:

    [...] En este post realizan un test de rendimiento en las diferentes operaciones de concatenacion de strings en Ruby. [...]

  3. David F Says:

    Oh dear. Don’t let Zed see this.

    Nice idea, but it’s not really statistically meaningful without knowledge of more parameters, environment, standard devs, etc.

  4. octoberdan Says:

    Results on my laptop show negligible differences between + and

  5. octoberdan Says:

    For some reason my last comment didn’t post fully, not sure why. I’ll try again…


    daniel@octobertop:~/project$ ruby -v && uname -a && ruby test.rb && ruby test.rbruby 1.8.5 (2006-08-25) [x86_64-linux]
    Linux octobertop 2.6.20-16-generic #2 SMP Thu Jun 7 19:00:28 UTC 2007 x86_64 GNU/Linux
    user system total real