Skip to content

Commit a196b23

Browse files
author
Manjunath
committed
Hash#update() vs Hash#[]=
1 parent 38f49f9 commit a196b23

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
@@ -859,6 +859,24 @@ Comparison:
859859
Hash#merge!: 10653.3 i/s - 2.66x slower
860860
```
861861

862+
##### `Hash#update` vs `Hash#[]=` [code](code/hash/update-vs-\[\]=.rb)
863+
864+
```
865+
$ ruby -v code/hash/update-vs-\[\]=.rb
866+
ruby 2.6.6p146 (2020-03-31 revision 67876) [x86_64-darwin18]
867+
868+
Warming up --------------------------------------
869+
Hash#[]= 7.453k i/100ms
870+
Hash#update 4.311k i/100ms
871+
Calculating -------------------------------------
872+
Hash#[]= 74.764k (± 1.9%) i/s - 380.103k in 5.085962s
873+
Hash#update 43.220k (± 0.8%) i/s - 219.861k in 5.087364s
874+
875+
Comparison:
876+
Hash#[]=: 74764.0 i/s
877+
Hash#update: 43220.1 i/s - 1.73x (± 0.00) slower
878+
```
879+
862880
##### `Hash#merge` vs `Hash#**other` [code](code/hash/merge-vs-double-splat-operator.rb)
863881

864882
```

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)