Skip to content

Commit

Permalink
Change: add another slicing method, and add a note about assuming all…
Browse files Browse the repository at this point in the history
… keys being in the Hash.
  • Loading branch information
kewlar committed Mar 1, 2023
1 parent 450d9cb commit 47e9ce1
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 34 deletions.
25 changes: 14 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1038,24 +1038,27 @@ Array#each_w/_object: 1352851.8 i/s - 1.88x slower
Hash#select-include : 760944.2 i/s - 3.34x slower
```

##### `Hash#values_at` vs `Hash#slice#values`
[code](code/hash/values_at-vs-slice-values.rb)
##### `Hash#values_at` vs `Hash#slice#values` vs `Array#map { Hash#[] }`
[code](code/hash/values_at-vs-map-vs-slice-values.rb)

To select hash values by keys.
To select hash values by keys, when all the keys exist in the hash.

```
$ ruby -v code/hash/values_at-vs-slice-values.rb
ruby 2.6.1p33 (2019-01-30 revision 66950) [x86_64-darwin18]
$ ruby -v code/hash/values_at-vs-map-vs-slice-values.rb
ruby 2.6.2p47 (2019-03-13 revision 67232) [x86_64-darwin18]
Warming up --------------------------------------
Hash#values_at 284.628k i/100ms
Hash#slice#values 230.279k i/100ms
Hash#values_at 298.254k i/100ms
Array#map 250.633k i/100ms
Hash#slice#values 243.267k i/100ms
Calculating -------------------------------------
Hash#values_at 7.179M (± 7.4%) i/s - 35.863M in 5.034179s
Hash#slice#values 4.458M (± 4.1%) i/s - 22.337M in 5.019922s
Hash#values_at 7.540M (± 1.5%) i/s - 37.878M in 5.025027s
Array#map 5.119M (± 2.3%) i/s - 25.815M in 5.045566s
Hash#slice#values 4.817M (± 1.7%) i/s - 24.083M in 5.001133s
Comparison:
Hash#values_at : 7178610.6 i/s
Hash#slice#values: 4458017.0 i/s - 1.61x slower
Hash#values_at : 7539658.6 i/s
Array#map : 5119405.7 i/s - 1.47x slower
Hash#slice#values: 4817081.6 i/s - 1.57x slower
```


Expand Down
30 changes: 30 additions & 0 deletions code/hash/values_at-vs-map-vs-slice-values.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
require 'benchmark/ips'

HASH = {
a: 'foo',
b: 'bar',
c: 'baz',
d: 'qux'
}.freeze

# Only keys that exist in the hash.
KEYS = %i[a c].freeze

def fast
HASH.values_at(*KEYS)
end

def slow
KEYS.map { |key| HASH[key] }
end

def slowest
HASH.slice(*KEYS).values
end

Benchmark.ips do |x|
x.report('Hash#values_at ') { fast }
x.report('Array#map { Hash#[] }') { slow }
x.report('Hash#slice#values ') { slowest }
x.compare!
end
23 changes: 0 additions & 23 deletions code/hash/values_at-vs-slice-values.rb

This file was deleted.

0 comments on commit 47e9ce1

Please sign in to comment.