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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With