Ruby:重复选择vs AND谓词?

如果我想选择满足谓词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)

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

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...