Concat strings on ruby

2021-02-03 ruby

I was wondering the difference between '+' and '<<' for String in Ruby. So wrote the sample codes like the below:

% cat s1.rb
s = ""
1000000.times do
  s += "a"
end
% cat s2.rb
s = ""
1000000.times do
  s = s << "a"
end

Then found the huge difference of the speed! '<<' is much faster than '+'!

% time ruby s1.rb
ruby s1.rb  1.25s user 1.57s system 99% cpu 2.838 total
% time ruby s2.rb
ruby s2.rb  0.09s user 0.05s system 91% cpu 0.152 total