LoginSignup
2
1

More than 5 years have passed since last update.

ある要素が含まれているかどうかの処理を各コレクションオブジェクトごとに計測

Posted at

include?メソッドの実行時間は
Array : O(n)
Hash : O(log n)
SetはHashと同じくらいらしい

ベンチマーク

ruby 2.3

benchmark.rb
require 'benchmark'
require 'set'

my_array = Array(1..1000)
my_set = Set.new(my_array)
my_hash = my_array.each_with_object({}) do |elem, obj|
  obj[elem] = true
end

select_state = Proc.new do |collection|
  collection.include?(500)
end

puts Benchmark::CAPTION

loop_num = 1000

puts Benchmark.measure {
  loop_num.times do |i|
    select_state.call(my_array)
  end
}

puts Benchmark.measure {
  loop_num.times do |i|
    select_state.call(my_set)
  end
}

puts Benchmark.measure {
  loop_num.times do |i|
    select_state.call(my_hash)
  end
}

実行結果

    user     system      total        real
0.000000   0.000000   0.000000 (  0.003784)
0.000000   0.000000   0.000000 (  0.000235)
0.000000   0.000000   0.000000 (  0.000188)

上からArray, Set, Hash

実行時間早くしたいならHash or Setだけどオブジェクトの生成コストとメモリ消費が少なそうなのはArray

2
1
0

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
2
1