-
Notifications
You must be signed in to change notification settings - Fork 375
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Added: other methods of slicing Hash values, when keys may not exist.
- Loading branch information
Showing
3 changed files
with
103 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
31 changes: 31 additions & 0 deletions
31
code/hash/values_at-compact-vs-slice-values-vs-map-compact.rb
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
require 'benchmark/ips' | ||
|
||
HASH = { | ||
a: 'foo', | ||
b: 'bar', | ||
c: 'baz', | ||
d: 'qux' | ||
}.freeze | ||
|
||
# Some of the keys may not exist in the hash; we don't care about the default values. | ||
KEYS = %i[a c e f].freeze | ||
|
||
# NOTE: This is the only correct method, if the default value of Hash may be not nil. | ||
def fast | ||
HASH.slice(*KEYS).values | ||
end | ||
|
||
def slow | ||
HASH.values_at(*KEYS).compact | ||
end | ||
|
||
def slowest | ||
KEYS.map { |key| HASH[key] }.compact | ||
end | ||
|
||
Benchmark.ips do |x| | ||
x.report('Hash#slice#values ') { fast } | ||
x.report('Hash#values_at#compact') { slow } | ||
x.report('Array#map#compact ') { slowest } | ||
x.compare! | ||
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
require 'benchmark/ips' | ||
|
||
HASH = { | ||
a: 'foo', | ||
b: 'bar', | ||
c: 'baz', | ||
d: 'qux' | ||
}.freeze | ||
|
||
# Some of the keys may not exist in the hash; we want to keep the default values. | ||
KEYS = %i[a c e f].freeze | ||
|
||
def fast | ||
HASH.values_at(*KEYS) | ||
end | ||
|
||
def slow | ||
KEYS.map { |key| HASH[key] } | ||
end | ||
|
||
Benchmark.ips do |x| | ||
x.report('Hash#values_at ') { fast } | ||
x.report('Array#map { Hash#[] }') { slow } | ||
x.compare! | ||
end |