Skip to content

Commit dbd4147

Browse files
committed
Add Range#cover? versus Range#include? example
1 parent 1ecd378 commit dbd4147

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

README.md

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -784,6 +784,29 @@ Comparison:
784784
```
785785

786786

787+
### Range
788+
789+
#### `cover?` vs `include?`
790+
791+
`cover?` only check if it is within the start and end, `include?` needs to traverse the whole range.
792+
793+
```
794+
$ ruby -v code/range/cover-vs-include.rb
795+
ruby 2.2.2p95 (2015-04-13 revision 50295) [x86_64-darwin14]
796+
797+
Calculating -------------------------------------
798+
Range#cover? 95.445k i/100ms
799+
Range#include? 9.326k i/100ms
800+
-------------------------------------------------
801+
Range#cover? 2.327M (± 4.7%) i/s - 11.644M
802+
Range#include? 99.652k (± 5.4%) i/s - 503.604k
803+
804+
Comparison:
805+
Range#cover?: 2327220.4 i/s
806+
Range#include?: 99651.6 i/s - 23.35x slower
807+
```
808+
809+
787810
## Less idiomatic but with significant performance ruby
788811

789812
Checkout: https://github.com/JuanitoFatas/fast-ruby/wiki/Less-idiomatic-but-with-significant-performance-diffrence

code/range/cover-vs-include.rb

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
require "benchmark/ips"
2+
require "date"
3+
4+
BEGIN_OF_JULY = Date.new(2015, 7, 1)
5+
END_OF_JULY = Date.new(2015, 7, 31)
6+
DAY_IN_JULY = Date.new(2015, 7, 15)
7+
8+
def fast
9+
(BEGIN_OF_JULY..END_OF_JULY).cover? DAY_IN_JULY
10+
end
11+
12+
def slow
13+
(BEGIN_OF_JULY..END_OF_JULY).include? DAY_IN_JULY
14+
end
15+
16+
Benchmark.ips do |x|
17+
x.report("Range#cover?") { fast }
18+
x.report("Range#include?") { slow }
19+
x.compare!
20+
end

0 commit comments

Comments
 (0)