2
我正在處理一些大型數據集,並試圖提高性能。我需要確定一個對象是否包含在一個數組中。我正在考慮使用index
或include?
,所以我對兩者都進行了基準測試。爲什麼array.index比array.include更快?
require 'benchmark'
a = (1..1_000_000).to_a
num = 100_000
reps = 100
Benchmark.bmbm do |bm|
bm.report('include?') do
reps.times { a.include? num }
end
bm.report('index') do
reps.times { a.index num }
end
end
令人驚訝的是(對我而言),index
速度相當快。
user system total real
include? 0.330000 0.000000 0.330000 ( 0.334328)
index 0.040000 0.000000 0.040000 ( 0.039812)
由於index
比include?
提供更多信息,我會希望它是稍微慢一些,如果有的話,雖然這種情況並非如此。爲什麼它更快?
(我知道index
直接從數組類來臨,include?
從可枚舉繼承。也許解釋了嗎?)
尼斯捕撈的討論,它不清醒時立即給我。我認爲你應該向MRI提交一個問題。 – 2014-09-11 06:02:26
相關:http://stackoverflow.com/questions/23729175/what-is-the-purpose-of-arrayinclude-as-compared-to-arrayindex – sawa 2014-09-11 06:15:12
@undur_gongor謝謝。 [完成](https://bugs.ruby-lang.org/issues/10227)。 – Sparhawk 2014-09-11 06:35:21