Skip to content

Commit da3e53c

Browse files
committed
Add Hash#[] versus Hash.fetch with Symbol and String as keys
1 parent e23c495 commit da3e53c

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

README.md

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -379,6 +379,33 @@ Comparison:
379379

380380
### Hash
381381

382+
#### `Hash#[]` vs `Hash.fetch` [code](code/hash/bracket-vs-fetch.rb)
383+
384+
If you use Ruby 2.2, `Symbol` could be more performant than `String` as `Hash` keys.
385+
Read more regarding this: [Symbol GC in Ruby 2.2](http://www.sitepoint.com/symbol-gc-ruby-2-2/) and [Unraveling String Key Performance in Ruby 2.2](http://www.sitepoint.com/unraveling-string-key-performance-ruby-2-2/).
386+
387+
```
388+
$ ruby -v code/hash/bracket-vs-fetch.rb
389+
ruby 2.2.2p95 (2015-04-13 revision 50295) [x86_64-darwin14]
390+
391+
Calculating -------------------------------------
392+
Hash#[], symbol 143.850k i/100ms
393+
Hash#fetch, symbol 137.425k i/100ms
394+
Hash#[], string 143.083k i/100ms
395+
Hash#fetch, string 120.417k i/100ms
396+
-------------------------------------------------
397+
Hash#[], symbol 7.531M (± 6.6%) i/s - 37.545M
398+
Hash#fetch, symbol 6.644M (± 8.2%) i/s - 32.982M
399+
Hash#[], string 6.657M (± 7.7%) i/s - 33.195M
400+
Hash#fetch, string 3.981M (± 8.7%) i/s - 19.748M
401+
402+
Comparison:
403+
Hash#[], symbol: 7531355.8 i/s
404+
Hash#[], string: 6656818.8 i/s - 1.13x slower
405+
Hash#fetch, symbol: 6643665.5 i/s - 1.13x slower
406+
Hash#fetch, string: 3981166.5 i/s - 1.89x slower
407+
```
408+
382409
##### `Hash#[]` vs `Hash#dup` [code](code/hash/bracket-vs-dup.rb)
383410

384411
Source: http://tenderlovemaking.com/2015/02/11/weird-stuff-with-hashes.html

code/hash/bracket-vs-fetch.rb

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
require "benchmark/ips"
2+
3+
HASH_WITH_SYMBOL = { fast: "ruby" }
4+
HASH_WITH_STRING = { "fast" => "ruby" }
5+
6+
def fastest
7+
HASH_WITH_SYMBOL[:fast]
8+
end
9+
10+
def faster
11+
HASH_WITH_SYMBOL.fetch(:fast)
12+
end
13+
14+
def fast
15+
HASH_WITH_STRING["fast"]
16+
end
17+
18+
def slow
19+
HASH_WITH_STRING.fetch("fast")
20+
end
21+
22+
Benchmark.ips do |x|
23+
x.report("Hash#[], symbol") { fastest }
24+
x.report("Hash#fetch, symbol") { faster }
25+
x.report("Hash#[], string") { fast }
26+
x.report("Hash#fetch, string") { slow }
27+
x.compare!
28+
end

0 commit comments

Comments
 (0)