diff --git a/README.md b/README.md index fecc33e..35013ef 100644 --- a/README.md +++ b/README.md @@ -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 ``` diff --git a/code/hash/values_at-vs-map-vs-slice-values.rb b/code/hash/values_at-vs-map-vs-slice-values.rb new file mode 100644 index 0000000..fdd1180 --- /dev/null +++ b/code/hash/values_at-vs-map-vs-slice-values.rb @@ -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 diff --git a/code/hash/values_at-vs-slice-values.rb b/code/hash/values_at-vs-slice-values.rb deleted file mode 100644 index fbb5451..0000000 --- a/code/hash/values_at-vs-slice-values.rb +++ /dev/null @@ -1,23 +0,0 @@ -require 'benchmark/ips' - -HASH = { - one: 'foo', - two: 'bar', - three: 'baz', - four: 'qux' -} -KEYS = %i[one three] - -def fast - HASH.values_at(*KEYS) -end - -def slow - HASH.slice(*KEYS).values -end - -Benchmark.ips do |x| - x.report('Hash#values_at ') { fast } - x.report('Hash#slice#values') { slow } - x.compare! -end