Uh oh!
There was an error while loading. Please reload this page.
Add Hash#values_at vs Array#map { Hash#[] } comparison - #174
Conversation
kewlar
commented
Mar 14, 2019
DO NOT MERGE YET. Just noticed that Will update the code and the benchmark, and see if it's still worth merging. |
Arcovion
commented
Mar 14, 2019
This is faster than KEYS.map{ |key| HASH[key]} |
kewlar
commented
Mar 14, 2019
@Arcovion, cool! Will add it to the benchmark, too. Thanks! |
Added more ways of slicing Hash values, and organized them into three separate cases:
Thoughts? |
etagwerker
commented
Feb 17, 2023
@kewlar I see the value in adding I'm happy to add code/hash/values_at-vs-map.rb if you submit just that in this PR or another PR. |
kewlar
commented
Mar 2, 2023
@etagwerker, thanks for the feedback! You're right, the other benchmarks are really just edge cases, and don't contribute much. And I've removed the redundant benchmarks. How does it look now? |
| d: 'qux' | ||
| }.freeze | ||
| # Some of the keys may not exist in the hash; we want to keep the default values. |
There was a problem hiding this comment.
For existing keys, the benchmark does not change much.
# frozen_string_literal: truerequire'benchmark/ips'HASH={a: 'foo',b: 'bar',c: 'baz',d: 'qux'}.freeze# the keys exist in the hashKEYS=%i[abcd].freezedeffastestHASH.values_at(*KEYS)enddefslowHASH.fetch_values(*KEYS)enddefslowestKEYS.map{ |key| HASH[key]}endBenchmark.ipsdo |x|
x.report('Hash#values_at '){fastest}x.report('Hash#fetch_values '){slow}x.report('Array#map { Hash#[] }'){slowest}x.compare!endydakuka@yauhenid:~/ruby-docker-app$ docker run ruby-app Warming up --------------------------------------Hash#values_at 405.669k i/100msHash#fetch_values 354.263k i/100msArray#map { Hash#[] } 221.960k i/100msCalculating -------------------------------------Hash#values_at 4.191M (± 4.7%) i/s - 21.095M in 5.045130sHash#fetch_values 3.895M (± 6.8%) i/s - 19.484M in 5.031663sArray#map { Hash#[] } 2.429M (± 6.1%) i/s - 12.208M in 5.048470sComparison:Hash#values_at : 4190993.6 i/sHash#fetch_values : 3894866.5 i/s - same-ish: difference falls within errorArray#map { Hash#[] }: 2429428.6 i/s - 1.73x slower
No description provided.