This post originated from an RSS feed registered with Java Buzz
by dion.
Original Post: Ruby append (
Feed Title: techno.blog(Dion)
Feed URL: http://feeds.feedburner.com/dion
Feed Description: blogging about life the universe and everything tech
A lot of developers know the dangers of concatenation with Strings and objects. In Java we had the StringBuffer.append vs. + (and now StringBuilder) knowledge transfer.
We ran into this issue in one of our projects, and I remember Dave Thomas talk about a problem that was fixed by moving from string concatenation to putting the contents on an array.
I think this benchmark says it all:
require 'benchmark'
Benchmark.bm do |x|
x.report do
a = 'foo'
100000.times { a += ' foo' }
end
x.report do
a = 'foo'
100000.times { a << ' foo' }
end
end
Output
dion@stewart [~]$ ruby t.rb
user system total real
13.790000 25.180000 38.970000 ( 40.102451)
0.060000 0.000000 0.060000 ( 0.064342)
So, favour << unless you really want to copy strings around.