.+ or .concat, what is faster for appending string in Ruby?

Problem:
I had to append around ~100-200K small strings (avg. length 7) to form a single large string . I had used + operator and it was very slow.

To find a faster alternative I did following benchmarking experiment:

Solution:

def bm_concat limit
  str = ""
  limit.times do
    str.concat("abcdefg")
  end
end

def bm_plus limit
  str = ""
  limit.times do
    str += "abcdefg"
  end
end

def diff t1, t2
  puts (t2-t1)
end

limit = ARGV[0]
which = ARGV[1]

puts "LIMIT: #{limit} , WHICH: #{which}"
if which == "plus"
  t = Time.now
  bm_plus limit.to_i
  t2 = Time.now
else
  t = Time.now
  bm_concat limit.to_i
  t2 = Time.now
end

diff(t,t2)

你可能感兴趣的:(.+ or .concat, what is faster for appending string in Ruby?)