Uh oh!
There was an error while loading. Please reload this page.
Hash#merge({}) vs Hash#dup#merge!({}) vs {}#merge!(Hash) - #42
Conversation
vs Hash#dup#merge!({}) vs {}#merge!(Hash)JuanitoFatas
commented
Aug 11, 2015
Thanks for the patch! I think Thanks again! |
bejmuller
commented
Aug 11, 2015
The reason of opening this PR was to show the difference between
I would have appreciated a comment first, and a possibility to reply before closing it right away... |
JuanitoFatas
commented
Aug 11, 2015
👍
My apologies. |
bejmuller
commented
Aug 11, 2015
No problem :) The description and the title I gave it are not the best, so that could have caused some confusion. |
JuanitoFatas
commented
Aug 11, 2015
Thank you Elod! I merged your commits in d83756f and made some minor changes 🙇 Thank you for your contribution 👍 🌠 🌠 🌠 🌠 🌠 |
krzysiek1507
commented
Apr 18, 2019
ENUM=(1..100)ORIGINAL_HASH={foo: {a: 1,b: {c: 3}},bar: {},baz: "baz",ruby: "ruby",test: "test",yup: "yup",rails: "rails"}deffastENUM.inject([])do |accumulator,element|
accumulator << ({bar: element}.merge!(ORIGINAL_HASH){ |_key,left,_right| left})endenddefslowENUM.inject([])do |accumulator,element|
accumulator << ORIGINAL_HASH.merge(bar: element)endenddefslow_dupENUM.inject([])do |accumulator,element|
accumulator << ORIGINAL_HASH.dup.merge!(bar: element)endendBenchmark.ipsdo |x|
x.report("{}#merge!(Hash) do end"){fast}x.report("Hash#merge({})"){slow}x.report("Hash#dup#merge!({})"){slow_dup}x.compare!endruby2.6.0p0(2018-12-25revision66547)[x86_64-darwin18]Warmingup --------------------------------------
{}#merge!(Hash) do end1.799k i/100msHash#merge({}) 2.956k i/100msHash#dup#merge!({}) 1.217k i/100msCalculating -------------------------------------
{}#merge!(Hash) do end18.216k(±1.7%) i/s - 91.749kin5.038319sHash#merge({}) 29.844k (± 2.9%) i/s - 150.756k in 5.056616sHash#dup#merge!({}) 12.288k (± 2.4%) i/s - 62.067k in 5.054204sComparison:
Hash#merge({}): 29844.0 i/s{}#merge!(Hash) do end: 18215.6 i/s - 1.64x slowerHash#dup#merge!({}): 12287.7 i/s - 2.43x slower |
In some cases we want duplicates of hashes to be created while merging, so I was wondering which one is the fastest way of achieving this: