1
我有一个散列数组,其密钥为Date
,值为Integer
。 这是一个模拟它的测试代码。为什么Range#include?比运算符大于或小于
hashes = 2000.times.map do |i|
[Date.new(2017) - i.days, rand(100)]
end.to_h
我想获取特定时期的值。 起初我用Range#include?
写了,但是速度很慢。
Benchmark.measure do
hashes.select{|k,v| (Date.new(2012,3,3)..Date.new(2012,6,10)).include?(k)}
end
#<Benchmark::Tms:0x007fd16479bed0 @label="", @real=2.9242447479628026, @cstime=0.0, @cutime=0.0, @stime=0.0, @utime=2.920000000000016, @total=2.920000000000016>
简单大于或小于运营商,它变得快了60倍。
Benchmark.measure do
hashes.select{|k,v| k >= Date.new(2012,3,3) && k <= Date.new(2012,6,10)}
end
#<Benchmark::Tms:0x007fd162b61670 @label="", @real=0.05436371313408017, @cstime=0.0, @cutime=0.0, @stime=0.0, @utime=0.05000000000001137, @total=0.05000000000001137>
我以为这两个表达基本相同。
为什么有这么大的差异?