moneybird / active-date-range

Powerful DateRanges for Ruby and ActiveSupport
MIT License
51 stars 0 forks source link

Include? behaves like cover? #7

Closed edwinv closed 3 years ago

edwinv commented 3 years ago

Ruby Range has different implementations for include? and cover?:

If begin and end are numeric, include? behaves like cover?

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)