simanのブログ

ゆるふわプログラマー。競技プログラミングやってます。Ruby好き

Rubyの文字列連結の速度比較

Rubyで文字列連結のメソッドの動作速度を比較してみました。

require 'benchmark'

Benchmark.bm do |x|
  NUM = 10000
  word = "Hello"

  x.report(:add) do
    str = ""

    NUM.times { str += word }
  end

  x.report(:concat) do
    str = ""

    NUM.times { str.concat(word) }
  end

  x.report(:shift) do
    str = ""

    NUM.times { str << word }
  end
end
       user     system      total        real
add  0.050000   0.050000   0.100000 (  0.098366)
concat  0.000000   0.000000   0.000000 (  0.001402)
shift  0.000000   0.000000   0.000000 (  0.001213)

結果としては「+=」が飛び抜けて遅かったです。理由としては連結の際に新しい文字列インスタンスを生成しているからだと思われます。「concat」や「<<」は高速に動作しますが、元のオブジェクトを破壊するので注意が必要です。