Ruby: String += vs <<

Learned this interesting tidbit on Seattle.rb mailing list that appending a string with << is 10 times more efficient than +=. This would matter if you are doing a lot of string concatenation.

From: Joe Van Dyk
Date: Fri, Nov 20, 2009 at 10:20 AM
Subject: Re: [Ruby] += vs <<
To: Seattle Ruby Brigade!

$ cat t.rb
require 'benchmark'

long_string = 's' * 100000000
another_long_string = 'y ' * 1000

Benchmark.bm do |b|
b.report("<<") { long_string << another_long_string }
b.report("+=") { long_string += another_long_string }
end

$ ruby t.rb
user system total real
<< 0.000000 0.020000 0.020000 ( 0.022544)
+= 0.110000 0.130000 0.240000 ( 0.250046)

Update: Later in this thread mentioned a comprehensive blog entry about this topic : The Fastest Way to Concatenate Strings and Arrays in Ruby

2 Comments
  1. November 21, 2009
  2. November 21, 2009