Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby differences between += and << to concatenate a string [duplicate]

Tags:

string

ruby

On Ruby 1.8.7 I was doing a loop concatenating strings when found out that there seems to be a HUGE difference between << and += on a String object:

 y = ""
 start = Time.now
 99999.times { |x| y += "some new string"  }
 puts "Time: #{Time.now - start}"
 # Time: 31.56718

 y=''
 start = Time.now
 99999.times { |x| y << "some new string"  }
 puts "Time: #{Time.now - start}"
 # Time: 0.018256

I google about that, found some results:

http://www.rubylove.info/post/1038516765/difference-between-string-concatenation-ruby-rails

Says that << modifies both strings, while += only modify the caller. I don't understand why is then << faster.

Next I went to the Ruby doc, but I wonder WHY there is no method +=

http://ruby-doc.org/core-2.2.0/String.html

like image 269
Arnold Roa Avatar asked May 01 '15 16:05

Arnold Roa


1 Answers

The shovel operator << performs much better than += when dealing with long strings because the shovel operator is allowed to modify the original string, whereas += has to copy all the text from the first string into a new string every time it runs.

There is no += operator defined on the String class, because += is a combined operator. In short x += "asdf" is exactly equivalent to x = x + "asdf", so you should reference the + operator on the string class, not look for a += operator.

like image 123
Ajedi32 Avatar answered Nov 07 '22 16:11

Ajedi32