Created
September 26, 2019 18:55
-
-
Save kbrock/86fb7def3f2fa285044cc2bab849161d to your computer and use it in GitHub Desktop.
Range.include was slow, running metrics
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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