Skip to content

Hash#merge({}) vs Hash#dup#merge!({}) vs {}#merge!(Hash) #42

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -544,6 +544,28 @@ Comparison:
Hash#merge: 409.6 i/s - 24.00x slower
```

##### `Hash#merge({})` vs `Hash#dup#merge!({})` vs `{}#merge!(Hash)` [code](code/hash/merge-vs-dup-merge-bang-vs-merge-bang.rb)

When we don't want to modify the original hash, and we want duplicates to be created

```
$ ruby -v code/hash/merge-vs-dup-merge-bang-vs-merge-bang.rb
ruby 2.2.2p95 (2015-04-13 revision 50295) [x86_64-linux]
Calculating -------------------------------------
Hash#merge({}) 603.000 i/100ms
Hash#dup#merge!({}) 650.000 i/100ms
{}#merge!(Hash) 1.763k i/100ms
-------------------------------------------------
Hash#merge({}) 6.593k (± 7.6%) i/s - 33.165k
Hash#dup#merge!({}) 6.591k (± 5.2%) i/s - 33.150k
{}#merge!(Hash) 17.654k (± 3.0%) i/s - 89.913k

Comparison:
{}#merge!(Hash): 17654.0 i/s
Hash#merge({}): 6592.7 i/s - 2.68x slower
Hash#dup#merge!({}): 6591.2 i/s - 2.68x slower
```

##### `Hash#sort_by` vs `Hash#sort` [code](code/hash/hash-key-sort_by-vs-sort.rb)

To sort hash by key.
Expand Down
29 changes: 29 additions & 0 deletions code/hash/merge-vs-dup-merge-bang-vs-merge-bang.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
require 'benchmark/ips'

ENUM = (1..100)
ORIGINAL_HASH = { key1: 'value 1' }

def slow
ENUM.inject([]) do |a, e|
a << ORIGINAL_HASH.merge(key2: e)
end
end

def slow_dup
ENUM.inject([]) do |a, e|
a << ORIGINAL_HASH.dup.merge!(key2: e)
end
end

def fast
ENUM.inject([]) do |a, e|
a << { key2: e }.merge!(ORIGINAL_HASH)
end
end

Benchmark.ips do |x|
x.report('Hash#merge({})') { slow }
x.report('Hash#dup#merge!({})') { slow_dup }
x.report('{}#merge!(Hash)') { fast }
x.compare!
end