本文介绍了数据结构:遍历两个数组VS在红宝石转换为集和执行相交操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以说我有 A1 A2

a1 = [1,2,3]
a2 = [4,2,5]

要查看是否 A1 A2 的元素,我可以遍历每比较每个元素:

To see if a1 shares any elements with a2, I can loop over each and compare each element:

def intersect?(x,y)
  a1.each do |x|
    a2.each do |y|
      if x == y return true
    end
  end
  false
end

但更容易,(a1.to_set&安培; a2.to_set)?present 给我相同的答案

我假设设定操作更快和更有效?如果这是真的,这是真的还是考虑到开销(如果有的话)的每个阵列上的 .to_set 操作?

I'm assuming that the set operation is quicker and more efficient? If this is true, is it still true taking into account to overhead (if any) of the .to_set operation on each array?

TIA

推荐答案

令人惊讶的是&安培; 阵列的方法比一套相当大集合速度快:

Surprisingly the & method of Array is faster than that of Set for quite large collections:

require 'set'
require 'benchmark'
f = 10_000
ar1 = (1..(10*f)).to_a # 100_000 elements
ar2 = ((5*f)..(15*f)).to_a # also 100_000 elements
set1 = ar1.to_set
set2 = ar2.to_set
n = 10

Benchmark.bm(10) do |testcase|
  testcase.report('Array'){ n.times{ ar1 & ar2 } }
  testcase.report('Set'){ n.times{ set1 & set2 } }
end

结果:

                 user     system      total        real
Array        1.380000   0.030000   1.410000 (  1.414634)
Set          2.310000   0.020000   2.330000 (  2.359317)

这篇关于数据结构:遍历两个数组VS在红宝石转换为集和执行相交操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 10:16