-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' }
x.report do
a = 'foo'
100000.times { a << ' foo' }


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.

12 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).


  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();
    String s = sb.toString();

  4. chanel replica handbags Says:

    thanks for your share,very good.thnaks!

  5. battery Says:


  6. battery Says:

    http://www.batteryfast.com/acer/travelmate-2000.htm acer travelmate 2000 battery,

  7. battery Says:

    http://www.batteryfast.co.uk/dell/inspiron-1150.htm dell inspiron 1150 battery,

  8. battery Says:

    http://www.batteryfast.com/laptop-ac-adapter/dell/DELL-19.5V-4.62A-90W-pin.php AC Adapter 4 Dell Inspiron 9T215 19.5V 4.62A 90W PA10

  9. battery Says:

    http://www.batteryfast.com/toshiba/1800.htm toshiba 1800 battery,

  10. battery Says:

    http://www.batteryfast.co.uk/asus/m3000-silver.htm asus m3000 silver battery,

  11. battery Says:

    http://www.batteryfast.co.uk/asus/m5n.htm asus m5n battery,

  12. battery boy Says:

    Ajax script apply, please refer http://www.battery-shop.org , the battery price loading by Ajax

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 is the number before 3? (just put in the digit)