Skip to content

Commit

Permalink
Merge pull request #195 from manjunath724/hash-update-vs-hash-brackets
Browse files Browse the repository at this point in the history
Hash#update() vs Hash#[]=
  • Loading branch information
kindoflew committed Apr 25, 2022
2 parents 1b4a509 + a196b23 commit bd5af46
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
18 changes: 18 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -878,6 +878,24 @@ Comparison:
Hash#merge!: 10653.3 i/s - 2.66x slower
```

##### `Hash#update` vs `Hash#[]=` [code](code/hash/update-vs-\[\]=.rb)

```
$ ruby -v code/hash/update-vs-\[\]=.rb
ruby 2.6.6p146 (2020-03-31 revision 67876) [x86_64-darwin18]
Warming up --------------------------------------
Hash#[]= 7.453k i/100ms
Hash#update 4.311k i/100ms
Calculating -------------------------------------
Hash#[]= 74.764k (± 1.9%) i/s - 380.103k in 5.085962s
Hash#update 43.220k (± 0.8%) i/s - 219.861k in 5.087364s
Comparison:
Hash#[]=: 74764.0 i/s
Hash#update: 43220.1 i/s - 1.73x (± 0.00) slower
```

##### `Hash#merge` vs `Hash#**other` [code](code/hash/merge-vs-double-splat-operator.rb)

```
Expand Down
21 changes: 21 additions & 0 deletions code/hash/update-vs-[]=.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
require 'benchmark/ips'

ENUM = (1..100)

def fast
ENUM.each_with_object({}) do |e, h|
h[e] = e
end
end

def slow
ENUM.each_with_object({}) do |e, h|
h.update(e => e)
end
end

Benchmark.ips do |x|
x.report('Hash#[]=') { fast }
x.report('Hash#update') { slow }
x.compare!
end

0 comments on commit bd5af46

Please sign in to comment.