Skip to content

Instantly share code, notes, and snippets.

@copremesis
Created November 7, 2012 22:57
Show Gist options
  • Save copremesis/4035153 to your computer and use it in GitHub Desktop.
Save copremesis/4035153 to your computer and use it in GitHub Desktop.
Sometimes abstraction kills performance
require 'benchmark'
Object.send(:remove_const, :DateRange)
class DateRange < Struct.new(:start_date, :end_date)
def good_include?(date)
(start_date..end_date).cover?(date)
end
def other_include?(date)
(date >= start_date && date <= end_date)
end
end
range = DateRange.new(1.year.ago, Time.now)
n = 50000
date = 10.months.ago
start_date, end_date = range.start_date, range.end_date
Benchmark.bm { |x|
x.report {
n.times { (start_date..end_date).cover?(date) }
}
x.report {
n.times { (date >= start_date && date <= end_date) }
}
}
# user system total real
# 0.540000 0.020000 0.560000 ( 0.588925)
# 0.270000 0.000000 0.270000 ( 0.266373)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment