如果我想选择满足谓词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)
因此,似乎这两种方法同样快.但是,比我知识渊博的人必须解释原因.
原文地址:https://www.jb51.cc/ruby/267609.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。