我想知道。在Ruby中測試數組是否包含另一個數組的最快方法是什麼?所以我建立這個小基準腳本。很想聽聽你對比較方法的想法。你知道其他一些 - 也許更好的方法來做到這一點?測試Ruby中數組包含的最快方法
require 'benchmark'
require 'set'
a = ('a'..'z').to_a.shuffle
b = ["b","d","f"]
Benchmark.bm do |x|
x.report do
10000.times do
Set[b].subset?(a.to_set)
end
end
x.report do
10000.times do
(a & b).count == b.size
end
end
x.report do
10000.times do
(a.inject(0) {|s,i| s += b.include?(i)?1:0 } == b.size)
end
end
x.report do
10000.times do
(b - a).empty?
end
end
x.report do
10000.times do
b.all? { |o| a.include? o }
end
end
end
和結果:
user system total real
0.380000 0.010000 0.390000 ( 0.404371)
0.050000 0.010000 0.060000 ( 0.075062)
0.140000 0.000000 0.140000 ( 0.140420)
0.130000 0.000000 0.130000 ( 0.136385)
0.030000 0.000000 0.030000 ( 0.034405)
你究竟想要比較什麼?他們有相同的尺寸或相同的元素?爲什麼不只是做一個== B? – elevine 2013-02-08 17:24:28
看起來他只是想知道b是a的一個子集。 – 2013-02-08 17:25:36
您應該多次運行每個部分(即,將每個部分都放在'10000.times do ... end'中)和/或使用更大的數組以獲得更有意義的結果。 – 2013-02-08 17:36:47