Ruby ファイルの読み込む「each」と「foreach」のパフォーマンスを計測する

  • 作成日 2021.12.20
  • 更新日 2022.03.02
  • Ruby
Ruby ファイルの読み込む「each」と「foreach」のパフォーマンスを計測する

Rubyで、benchmarkを使用して、ファイルの読み込む「each」と「foreach」のパフォーマンスを計測するサンプルコードを記述してます。rubyのバージョンは2.7.2を使用してます。

環境

  • OS windows10 pro 64bit
  • ruby 2.7.2p137

パフォーマンス計測

benchmarkを使用して、「each」と「foreach」を使用して、ファイルの読み込みを行うコードを10万回実行したパフォーマンスを計測するサンプルコードとなります。

require "benchmark"

# 繰り返し回数 10万回
i = 100_000

# 10は、reportラベルに使用する桁数
Benchmark.bm 10 do |r|
  r.report "#each" do
    i.times do
      open("hoge.txt").each do |line|
      end
    end
  end

  r.report "#foreach" do
    i.times do
      File.foreach("hoge.txt") do |line|
      end
    end
  end
end

実行結果

<1回目>
                 user     system      total        real
#each        1.390000   4.312000   5.702000 (  5.699432)
#foreach     1.219000   4.578000   5.797000 (  5.798454)

<2回目>
                 user     system      total        real
#each        1.516000   4.109000   5.625000 (  5.624679)
#foreach     1.687000   4.094000   5.781000 (  5.790927)

<3回目>
                 user     system      total        real
#each        1.500000   4.328000   5.828000 (  5.817134)
#foreach     1.375000   4.579000   5.954000 (  5.949066)

どちらを使用しても、ほぼ同じ結果となりました。