Skip to content

Commit 84a01ad

Browse files
committed
Explain the Hash#fetch example in more detail
1 parent 127e360 commit 84a01ad

File tree

2 files changed

+18
-20
lines changed

2 files changed

+18
-20
lines changed

README.md

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -462,21 +462,25 @@ Comparison:
462462

463463
##### `Hash#fetch` with argument vs `Hash#fetch` + block [code](code/hash/fetch-vs-fetch-with-block.rb)
464464

465-
```
466-
$ ruby -v code/hash/fetch-vs-fetch-with-block.rb
467-
ruby 2.2.1p85 (2015-02-26 revision 49769) [x86_64-darwin14]
465+
> Note that the speedup in the block version comes from avoiding repeated
466+
> construction of the argument. If the argument is a constant, number symbol or
467+
> something of that sort the argument version is actually slightly faster
468468
469+
$ ruby -v code/hash/fetch-vs-fetch-with-block.rb
470+
ruby 2.2.0p0 (2014-12-25 revision 49005) [x86_64-darwin13]
469471
Calculating -------------------------------------
470-
Hash#fetch + block 139.880k i/100ms
471-
Hash#fetch + arg 119.645k i/100ms
472+
Hash#fetch + const 129.868k i/100ms
473+
Hash#fetch + block 125.254k i/100ms
474+
Hash#fetch + arg 121.155k i/100ms
472475
-------------------------------------------------
473-
Hash#fetch + block 6.116M (± 8.9%) i/s - 30.354M
474-
Hash#fetch + arg 4.473M (± 9.9%) i/s - 22.134M
476+
Hash#fetch + const 7.031M (± 7.0%) i/s - 34.934M
477+
Hash#fetch + block 6.815M (± 4.2%) i/s - 34.069M
478+
Hash#fetch + arg 4.753M (± 5.6%) i/s - 23.746M
475479

476480
Comparison:
477-
Hash#fetch + block: 6116059.5 i/s
478-
Hash#fetch + arg: 4472636.0 i/s - 1.37x slower
479-
```
481+
Hash#fetch + const: 7030600.4 i/s
482+
Hash#fetch + block: 6814826.7 i/s - 1.03x slower
483+
Hash#fetch + arg: 4752567.2 i/s - 1.48x slower
480484

481485
##### `Hash#each_key` instead of `Hash#keys.each` [code](code/hash/keys-each-vs-each_key.rb)
482486

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,11 @@
11
require "benchmark/ips"
22

33
HASH = { writing: :fast_ruby }
4-
5-
def fast
6-
HASH.fetch(:writing) { "fast ruby" }
7-
end
8-
9-
def slow
10-
HASH.fetch(:writing, "fast ruby")
11-
end
4+
DEFAULT = "fast ruby"
125

136
Benchmark.ips do |x|
14-
x.report("Hash#fetch + block") { fast }
15-
x.report("Hash#fetch + arg") { slow }
7+
x.report("Hash#fetch + const") { HASH.fetch(:writing, DEFAULT) }
8+
x.report("Hash#fetch + block") { HASH.fetch(:writing) { "fast ruby" } }
9+
x.report("Hash#fetch + arg") { HASH.fetch(:writing, "fast ruby") }
1610
x.compare!
1711
end

0 commit comments

Comments
 (0)