加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ruby:重复选择vs AND谓词?

发布时间:2020-12-16 21:18:01 所属栏目:百科 来源:网络整理
导读:如果我想选择满足谓词p_1和p_2的数组arr的所有元素,那么我有两个实现选项: 选项1: arr.select{|x| x.p_1}.select{|x| x.p_2} 选项2: arr.select{|x| x.p_1 x.p_2} 这两者之间有显着差异吗?在我的用例中,谓词p_1比p_2减少了更多的列表,而p_2比p_1更贵.因
如果我想选择满足谓词p_1和p_2的数组arr的所有元素,那么我有两个实现选项:

选项1:

arr.select{|x| x.p_1}.select{|x| x.p_2}

选项2:

arr.select{|x| x.p_1 && x.p_2}

这两者之间有显着差异吗?在我的用例中,谓词p_1比p_2减少了更多的列表,而p_2比p_1更贵.因此我怀疑在p_2之前将p_1放得更快.但是,上述任何一个选项都有所作为吗?

解决方法

根据你所说的,我已经做了一个基准测试:
require 'benchmark'

N = 1000

# the fast method
def p1(arr_param)
  # lazy init of the arr_param,so it returns 20 times true and 80 times false
  (arr_param << Array.new(20,true) << Array.new(80,false)).flatten! if arr_param.empty?

  # shorter sleep
  t = Time.now.to_f
  while true
    break if Time.now.to_f - t > 0.000_01
  end
  arr_param.shift
end

# the slow method
def p2
  # longer sleep
  t = Time.now.to_f
  while true
    break if Time.now.to_f - t > 0.001
  end
  true
end

# testing arrays
arr = (1..100).to_a
truth_arr = []

Benchmark.bm(7) do |b|
  b.report('chain') { N.times { arr.select { |_| p1(truth_arr) }.select { |_| p2 } } }
  b.report('and') { N.times { arr.select { |_| p1(truth_arr) && p2 } } }
end

结果是:

#=>              user     system      total        real
#=> chain    78.422000   0.000000  78.422000 ( 78.789006)
#=> and      78.375000   0.000000  78.375000 ( 79.313160)

因此,似乎这两种方法同样快.但是,比我知识渊博的人必须解释原因.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读