Last active
December 1, 2015 19:44
-
-
Save devpuppy/b3bde744cea910c6ca45 to your computer and use it in GitHub Desktop.
perf comp of Hash#hmap implementations
This file contains hidden or 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
require 'benchmark/ips' | |
# hash.size # 1000 | |
# hash.values.flatten.size # 500500 | |
def a_big_hash | |
{}.tap do |h| | |
1.upto(1000) { |i| h[i.to_s.to_sym] = 1.upto(i).to_a } | |
end | |
end | |
class Hash | |
# map to_h | |
def hmap1 &block | |
self.map(&block).to_h | |
end | |
# tap each | |
def hmap2 &block | |
{}.tap do |h| | |
each do |i| | |
k, v = block.call(i) | |
h[k] = v | |
end | |
end | |
end | |
# reduce | |
def hmap3 &block | |
reduce({}) do |acc, i| | |
pair = block.call(i) | |
acc.merge({pair[0] => pair[1].size}) | |
end | |
end | |
# map reduce | |
def hmap4 &block | |
map { |i| | |
k, v = block.call(i) | |
{k => v} | |
}.reduce(:merge) | |
end | |
# brackets splat flat_map | |
def hmap5 &block | |
Hash[*flat_map(&block)] | |
end | |
end | |
Benchmark.ips do |bm| | |
bm.time = 10 | |
bm.warmup = 5 | |
hash = a_big_hash.freeze # nothing should attempt to mutate hash | |
counter = proc { |k, v| [k, v.size] } | |
bm.report 'map to_h' do | |
hash.hmap1 &counter | |
end | |
bm.report 'tap each' do | |
hash.hmap2 &counter | |
end | |
bm.report 'reduce' do | |
hash.hmap3 &counter | |
end | |
bm.report 'map reduce' do | |
hash.hmap4 &counter | |
end | |
bm.report '[] splat flat_map' do | |
hash.hmap5 &counter | |
end | |
bm.compare! | |
end | |
# Calculating ------------------------------------- | |
# map to_h 110.000 i/100ms | |
# tap each 88.000 i/100ms | |
# reduce 1.000 i/100ms | |
# map reduce 1.000 i/100ms | |
# [] splat flat_map 116.000 i/100ms | |
# ------------------------------------------------- | |
# map to_h 1.374k (±19.7%) i/s - 13.310k | |
# tap each 926.439 (±25.7%) i/s - 8.536k | |
# reduce 3.397 (±29.4%) i/s - 33.000 | |
# map reduce 3.596 (±27.8%) i/s - 35.000 | |
# [] splat flat_map 1.246k (±19.5%) i/s - 11.948k | |
# Comparison: | |
# map to_h: 1373.5 i/s | |
# [] splat flat_map: 1245.5 i/s - 1.10x slower | |
# tap each: 926.4 i/s - 1.48x slower | |
# map reduce: 3.6 i/s - 381.94x slower | |
# reduce: 3.4 i/s - 404.28x slower |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment