File tree Expand file tree Collapse file tree 2 files changed +43
-0
lines changed Expand file tree Collapse file tree 2 files changed +43
-0
lines changed Original file line number Diff line number Diff 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
789812Checkout: https://github.com/JuanitoFatas/fast-ruby/wiki/Less-idiomatic-but-with-significant-performance-diffrence
Original file line number Diff line number Diff line change 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
You can’t perform that action at this time.
0 commit comments