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 @@ -963,6 +963,26 @@ Array#each_w/_object: 1352851.8 i/s - 1.88x slower
963963Hash#select-include : 760944.2 i/s - 3.34x slower
964964```
965965
966+ ##### ` Hash#values_at ` vs ` Hash#slice#values `
967+ [ code] ( code/hash/values_at-vs-slice-values.rb )
968+
969+ To select hash values by keys.
970+
971+ ```
972+ $ ruby -v code/hash/values_at-vs-slice-values.rb
973+ ruby 2.6.1p33 (2019-01-30 revision 66950) [x86_64-darwin18]
974+ Warming up --------------------------------------
975+ Hash#values_at 284.628k i/100ms
976+ Hash#slice#values 230.279k i/100ms
977+ Calculating -------------------------------------
978+ Hash#values_at 7.179M (± 7.4%) i/s - 35.863M in 5.034179s
979+ Hash#slice#values 4.458M (± 4.1%) i/s - 22.337M in 5.019922s
980+
981+ Comparison:
982+ Hash#values_at : 7178610.6 i/s
983+ Hash#slice#values: 4458017.0 i/s - 1.61x slower
984+ ```
985+
966986
967987### Proc & Block
968988
Original file line number Diff line number Diff line change 1+ require 'benchmark/ips'
2+
3+ HASH = {
4+ one : 'foo' ,
5+ two : 'bar' ,
6+ three : 'baz' ,
7+ four : 'qux'
8+ }
9+ KEYS = %i[ one three ]
10+
11+ def fast
12+ HASH . values_at ( *KEYS )
13+ end
14+
15+ def slow
16+ HASH . slice ( *KEYS ) . values
17+ end
18+
19+ Benchmark . ips do |x |
20+ x . report ( 'Hash#values_at ' ) { fast }
21+ x . report ( 'Hash#slice#values' ) { slow }
22+ x . compare!
23+ end
You can’t perform that action at this time.
0 commit comments