美文网首页
.+ or .concat, what is faster fo

.+ or .concat, what is faster fo

作者: 柳辉 | 来源:发表于2017-08-17 15:57 被阅读8次

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 fo

      本文链接:https://www.haomeiwen.com/subject/ijcnrxtx.html