-1 on +1 Getting Tarpitted
Sep 29

Ruby append (<<) versus concat (+)

Ruby, Tech Add comments

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.

Ruby has the same issue, and people have talked about it before.

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.

3 Responses to “Ruby append (<<) versus concat (+)”

  1. Daniel Berger Says:

    I’m not really sure this is an “issue”. You need both behaviors or someone will scream.

    This is pretty old news, btw.

    - Dan

  2. Dion Almaer Says:

    You definitely do need both.

    I also know this is old, but a lot of new ruby programmers have been caught on this one recently.

    It is much more intuitive to do “foo” + “bar” for many new rubyists, and they do not know the downside (until it hits them).

    Dion

  3. Brian Pontarelli Says:

    Java also tries to help you out by converting chains of + concats to StringBuilder under the hoods when compiling. Doesn’t help the looping example you have above, but works on stuff like:

    String s = “foo” + s1 + “bar” + s2 + “baz” + s3;

    This creates the same number and type of Objects as:

    StringBuilder sb = new StringBuilder();
    sb.append(”foo”).append(s1).append(”bar”).append(s2).append(”baz”).append(s3);
    String s = sb.toString();

Leave a Reply

Spam is a pain, I am sorry to have to do this to you, but can you answer the question below?

Q: What are the first four letters in the world British?