join() is slower than the

Turns out the Internet was right on this one: if you’re trying to create a big string from little ones it’s faster to << (less-than-less-than operator) on a String than to make an array of Strings and join its elements. Without diving into the Ruby code itself my guess is that strings are linked lists in memory and its end pointer is just moved, whereas making a bunch of array elements means new String objects for each and then having to walk all of the objects to form a new String in the end. (Granted, I’m using Ruby 1.8.7 still!)

Here’s the code:

require 'benchmark'
Benchmark.bm(20) do |x|
  x.report('join') do
    1_000.times do
      a = []
      1_000.times do
        a << 'This is some string stuff'
      end
      a.join
    end
  end
  x.report('<<') do
    1_000.times do
      a = ''
      1_000.times do
        a << 'This is some string stuff'
      end
      a
    end
  end
end

And the result:

          user     system      total      real
join  1.180000   0.390000   1.570000 (1.571057)
<<    1.090000   0.390000   1.480000 (1.491420)

Leave a Reply