1
這裏是我的腳本堆棧水平紅寶石陣太深VS哈希測試
require 'benchmark'
require 'ostruct'
Benchmark.bmbm do |x|
n=10000
array = n.times.map{ |i| OpenStruct.new id: i }
hash = Hash[*(array.map{ |s| [s.id, s] }.flatten)]
x.report('array') do
array.find{ |s| s.id == 100}
end
x.report('hash') do
hash[100]
end
end
爲什麼用n=100000
我得到:
stack level too deep (SystemStackError)
?
不相關,但是,我是以最好的方式構建散列嗎?
哈希查找總是比'陣列快。 find'和'OpenStruct'不是正確的使用方法,因爲它使用'method_missing'來構建它的屬性 – bjhaid
@bjhaid我認爲任何基準測試都不一定是「愚蠢的」。有人找到並證明哈希查找速度更快的更好方法是什麼? –
什麼是正確的事情? – juanpastas