Skip to content

Instantly share code, notes, and snippets.

@kbrock
Created September 26, 2019 18:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kbrock/86fb7def3f2fa285044cc2bab849161d to your computer and use it in GitHub Desktop.
Save kbrock/86fb7def3f2fa285044cc2bab849161d to your computer and use it in GitHub Desktop.
Range.include was slow, running metrics
#!/usr/bin/env ruby
require "benchmark/ips"
require "date"
BEGIN_OF_JULY = Date.new(2015, 7, 1)
END_OF_JULY = Date.new(2015, 7, 31)
DAY_IN_JULY = Date.new(2015, 7, 15)
RANGE = BEGIN_OF_JULY..END_OF_JULY
Benchmark.ips(:warmup => 1) do |x|
x.report('range#cover?') { (BEGIN_OF_JULY..END_OF_JULY).cover? DAY_IN_JULY }
x.report('range2#cover?') { RANGE.cover? DAY_IN_JULY } # WINNER
x.report('range#include?') { RANGE.include? DAY_IN_JULY }
x.report('range#member?') { RANGE.member? DAY_IN_JULY }
x.report('range#compare') { RANGE.begin <= DAY_IN_JULY && (RANGE.exclude_end? ? DAY_IN_JULY < RANGE.end : DAY_IN_JULY <= RANGE.end) }
x.report('plain compare') { BEGIN_OF_JULY < DAY_IN_JULY && DAY_IN_JULY < END_OF_JULY } # SECOND
x.compare!
end
# as long as you are not creating a range for every call, cover is the fastest
# Comparison:
# range2#cover?: 4523430.0 i/s
# plain compare: 3790571.8 i/s - 1.19x slower
# range#compare: 3134619.1 i/s - 1.44x slower
# range#cover?: 2884907.0 i/s - 1.57x slower
# range#member?: 95400.5 i/s - 47.42x slower
# range#include?: 94959.3 i/s - 47.64x slower
# interesting that all the logic in range#compare is faster than dealing with object creation of the ranges
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment