File tree Expand file tree Collapse file tree 2 files changed +40
-0
lines changed Expand file tree Collapse file tree 2 files changed +40
-0
lines changed Original file line number Diff line number Diff line change @@ -937,6 +937,24 @@ Comparison:
937937 sort + to_h: 81972.8 i/s - 1.49x slower
938938```
939939
940+ ##### ` Hash#slice ` vs ` Hash#select{ includes? } ` [ code] ( code/hash/slice-vs-select-include.rb )
941+
942+ Since ruby 2.5, Hash comes with a ` slice ` method to select hash members by keys.
943+
944+ ```
945+ $ ruby code/hash/slice-vs-select-include.rb
946+ ruby 2.5.3p105 (2018-10-18 revision 65156) [x86_64-linux]
947+
948+ Calculating -------------------------------------
949+ Hash#slice 3.124M (± 0.6%) i/s - 15.675M in 5.017984s
950+ Hash#select_if_includes
951+ 1.342M (± 1.1%) i/s - 6.716M in 5.003901s
952+
953+ Comparison:
954+ Hash#slice: 3123803.2 i/s
955+ Hash#select_if_includes: 1342270.6 i/s - 2.33x slower
956+ ```
957+
940958### Proc & Block
941959
942960##### Block vs ` Symbol#to_proc ` [ code] ( code/proc-and-block/block-vs-to_proc.rb )
Original file line number Diff line number Diff line change 1+ require 'benchmark/ips'
2+
3+ HASH = {
4+ title : "awesome" ,
5+ description : "a description" ,
6+ author : "styd" ,
7+ published_at : Time . now
8+ }
9+
10+ def fast
11+ HASH . slice ( :title , :author )
12+ end
13+
14+ def slow
15+ HASH . select { |k , _ | [ :title , :author ] . include? k }
16+ end
17+
18+ Benchmark . ips do |x |
19+ x . report ( 'Hash#slice' ) { fast }
20+ x . report ( 'Hash#select_if_includes' ) { slow }
21+ x . compare!
22+ end
You can’t perform that action at this time.
0 commit comments