Skip to content

Commit bd5af46

Browse files
authored
Merge pull request #195 from manjunath724/hash-update-vs-hash-brackets
Hash#update() vs Hash#[]=
2 parents 1b4a509 + a196b23 commit bd5af46

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

README.md

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -878,6 +878,24 @@ Comparison:
878878
Hash#merge!: 10653.3 i/s - 2.66x slower
879879
```
880880

881+
##### `Hash#update` vs `Hash#[]=` [code](code/hash/update-vs-\[\]=.rb)
882+
883+
```
884+
$ ruby -v code/hash/update-vs-\[\]=.rb
885+
ruby 2.6.6p146 (2020-03-31 revision 67876) [x86_64-darwin18]
886+
887+
Warming up --------------------------------------
888+
Hash#[]= 7.453k i/100ms
889+
Hash#update 4.311k i/100ms
890+
Calculating -------------------------------------
891+
Hash#[]= 74.764k (± 1.9%) i/s - 380.103k in 5.085962s
892+
Hash#update 43.220k (± 0.8%) i/s - 219.861k in 5.087364s
893+
894+
Comparison:
895+
Hash#[]=: 74764.0 i/s
896+
Hash#update: 43220.1 i/s - 1.73x (± 0.00) slower
897+
```
898+
881899
##### `Hash#merge` vs `Hash#**other` [code](code/hash/merge-vs-double-splat-operator.rb)
882900

883901
```

code/hash/update-vs-[]=.rb

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
require 'benchmark/ips'
2+
3+
ENUM = (1..100)
4+
5+
def fast
6+
ENUM.each_with_object({}) do |e, h|
7+
h[e] = e
8+
end
9+
end
10+
11+
def slow
12+
ENUM.each_with_object({}) do |e, h|
13+
h.update(e => e)
14+
end
15+
end
16+
17+
Benchmark.ips do |x|
18+
x.report('Hash#[]=') { fast }
19+
x.report('Hash#update') { slow }
20+
x.compare!
21+
end

0 commit comments

Comments
 (0)