Ruby 複数の変数に代入する3つの方法のそれぞれのパフォーマンスを計測する

Ruby 複数の変数に代入する3つの方法のそれぞれのパフォーマンスを計測する

Rubyで、benchmarkを使用して、複数の変数に代入する3つの方法のそれぞれのパフォーマンスを計測するサンプルコードを記述してます。rubyのバージョンは2.7.2を使用してます。

環境

  • OS windows10 pro 64bit
  • ruby 2.7.2p137

パフォーマンス計測

benchmarkを使用して、通常の「=」で1つずとと、「,」で1行で多重代入とと「配列」を使用した、変数の代入するコードを1000万回呼び出したパフォーマンスを計測するサンプルコードとなります。

require "benchmark"

# 繰り返し回数 1000万回
i = 10_000_000

# 10は、reportラベルに使用する桁数
Benchmark.bm 10 do |r|
  r.report "#通常" do
    i.times do
      str1 = "hello"
      str2 = "world"
      str3 = "!!"
    end
  end

  r.report "#多重代入" do
    i.times do
      str4, str5, str6 = "hello", "world", "!!"
    end
  end

  r.report "#配列" do
    i.times do
      str7, str8, str9 = ["hello", "world", "!!"]
    end
  end
end

実行結果

<1回目>
                 user     system      total        real
#通常          0.860000   0.000000   0.860000 (  0.870090)
#多重代入        1.156000   0.000000   1.156000 (  1.152807)
#配列          1.141000   0.000000   1.141000 (  1.130772)

<2回目>
                 user     system      total        real
#通常          0.859000   0.000000   0.859000 (  0.861680)
#多重代入        1.125000   0.000000   1.125000 (  1.125333)
#配列          1.125000   0.000000   1.125000 (  1.126306)

<3回目>
                 user     system      total        real
#通常          0.859000   0.000000   0.859000 (  0.868006)
#多重代入        1.204000   0.000000   1.204000 (  1.204764)
#配列          1.187000   0.000000   1.187000 (  1.189192)

1つずつ代入した方するのが一番早そうです。