環境
$ uname -mrs
Linux 2.6.32-220.4.2.el6.x86_64 x86_64
Ruby version
ruby 1.8.7 (2012-02-08 MBARI 8/0x6770 on patchlevel 358) [x86_64-linux], MBARI 0x6770, Ruby Enterprise Edition 2012.02
require 'benchmark'
Document = Struct.new(:id,:a,:b,:c)
documents_a = []
documents_h = {}
1.upto(10_000) do |n|
d = Document.new(n)
documents_a << d
documents_h[d.id] = true
end
searchlist = Array.new(1000){ rand(10_000)+1 }
Benchmark.bm(10) do |x|
x.report('array_any?'){searchlist.each{|el| documents_a.any?{|d| d.id == el}} }
x.report('array_include?'){searchlist.each{|el| documents_a.include?(el)} }
x.report('hash_has_key?'){searchlist.each{|el| documents_h.has_key?(el)} }
x.report('hash'){searchlist.each{|el| documents_h[el] } }
end
結果(當array 與 hash 資料有 10,000筆時):
user system total real
array_any? 5.350000 0.000000 5.350000 ( 5.367080)
array_include? 0.890000 0.000000 0.890000 ( 0.887109)
hash_has_key? 0.000000 0.000000 0.000000 ( 0.000420)
hash 0.000000 0.000000 0.000000 ( 0.002201)
結果(當array 與 hash 資料有 100,000筆時):
user system total real
array_any? 5.970000 0.000000 5.970000 ( 5.979810)
array_include? 10.650000 0.000000 10.650000 ( 10.656045)
hash_has_key? 0.000000 0.000000 0.000000 ( 0.000545)
hash 0.000000 0.000000 0.000000 ( 0.000968)
看起來用 hash 是最快的, 但是array 的include? 在資料筆數大的時候, 居然慢比any?還慢.
相關來源:
http://stackoverflow.com/questions/5551168/performance-of-arrays-and-hashes-in-ruby
沒有留言:
張貼留言