我想知道。在 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)