LoginSignup
0
0

More than 5 years have passed since last update.

Rubyで配列を結合して和集合取るときのパフォーマンス

Last updated at Posted at 2019-01-18

配列と配列を結合して重複を取り除きたい!
そんなときに書き方で迷ったのでめも。

※追記:計測方法をBenchmarkに変更。Setを使った方法を追加。(コメント頂いた @takaramさん@scivolaさんありがとうございます!!!)

どっちが効率いいの?

array1 |= array2
array1.concat(array2).uniq!
Set#merge
Set <<

結論

②のほうが2.7倍はやい!←Beanchmark未使用
④が優勝!
というかSet使った③と④が圧倒的に早い!!

すごいぞSet!!
Setクラスでの集合

Benchmarkを使った計測

                   user     system      total        real
|=            21.300000   0.110000  21.410000 ( 21.447536)
concat.uniq!  22.110000   0.030000  22.140000 ( 22.163939)
Set merge      1.090000   0.000000   1.090000 (  1.087682)
Set <<         0.250000   0.000000   0.250000 (  0.253353)
n = 1_000_000
m = 1

Benchmark.bm(12) do |x|
  x.report("|=") do
    m.times do
      arr = []
      n.times { arr |= [rand(100)] }
    end
  end

  x.report("concat.uniq!") do
    m.times do
      arr = []
      n.times { arr.concat([rand(100)]).uniq! }
    end
  end

  x.report("Set merge") do
    m.times do
      s = Set.new
      n.times { s.merge([rand(100)]) }
    end
  end

  x.report("Set <<") do
    m.times do
      s = Set.new
      n.times { s << rand(100) }
    end
  end
end

以下Benchmark未使用の計測

s = Time.now
arr = []
100000.times do |i| arr |= [rand(100)] end
puts Time.now - s
# 2.124894

s = Time.now
arr = []
100000.times do |i| arr.concat([rand(100)]).uniq! end
puts Time.now - s
# 0.788314
0
0
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0