Ruby Range has different implementations for include? and cover?:
include? will try to find the element in the range. Only when begin and end are numeric, it will behave like cover?:
If begin and end are numeric, include? behaves like cover?
cover? will test if the element is between begin and end:
This tests begin <= obj <= end when exclude_end? is false and begin <= obj < end when exclude_end? is true.
There is a clear performance benefit from using cover? instead of include?. For ranges of dates, it is better to use cover?, because we have a continuous spectrum of dates. Therefore, the include? method now always calls cover? to have the performance benefit from it:
range = ActiveDateRange::DateRange.this_year
day = Date.current
Benchmark.bm do |x|
x.report("include?") { 1000.times { range.include?(day) } }
x.report("cover?") { 1000.times { range.cover?(day) } }
x.report("begin <= obj <= end") { 1000.times { day >= range.begin && day <= range.end } }
end
user system total real
include? 0.127010 0.004048 0.131058 ( 0.132353)
cover? 0.000215 0.000000 0.000215 ( 0.000215)
begin <= obj <= end 0.000264 0.000000 0.000264 ( 0.000265)
Ruby
Range
has different implementations forinclude?
andcover?
:include?
will try to find the element in the range. Only whenbegin
andend
are numeric, it will behave likecover?
:cover?
will test if the element is betweenbegin
andend
:There is a clear performance benefit from using
cover?
instead ofinclude?
. For ranges of dates, it is better to usecover?
, because we have a continuous spectrum of dates. Therefore, theinclude?
method now always callscover?
to have the performance benefit from it: