Saari Development

Ali Rizvi's Technical Blog as a Professional Software Development Engineer

Ruby: String += vs <<

with 2 comments

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

Advertisements

Written by imsaar

November 20, 2009 at 8:44 pm

Posted in ruby

2 Responses

Subscribe to comments with RSS.

  1. One should also not forget that << will modify the original string.

      original_string = "Hello, "
      hi = original_string
      there = "World"
      hi < true
    

    Waseem Ahmad

    November 21, 2009 at 6:33 am

  2. Bad HTML!!!

      original_string = "Hello, "
      hi original_string
      there = "World"
      hi << there
      assert_equal "Hello, World", original_string
    

    Waseem Ahmad

    November 21, 2009 at 6:35 am


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: