Created
June 1, 2015 16:53
-
-
Save fny/25b3fc558516636474dd to your computer and use it in GitHub Desktop.
Benchmarks for different ways of remapping the values of a hash
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
require 'benchmark/ips' | |
MONDO_HASH = (1..50).each_with_object({}) { |num, hash| | |
hash[num.to_s] = num | |
} | |
# Monkey-patching a map_values to test; this should probably be a refinement | |
class Hash | |
def map_values | |
merge({}) { |key, value| yield(value) } | |
end | |
end | |
Benchmark.ips do |x| | |
# Only run the GC before and after each benchmark | |
x.config(:suite => Class.new { | |
def warming(*); run_gc; end | |
def running(*); run_gc; end | |
def warmup_stats(*); end | |
def add_report(*); end | |
private | |
def run_gc | |
GC.enable | |
GC.start | |
GC.disable | |
end | |
}.new) | |
x.report("each_with_object") { | |
MONDO_HASH.each_with_object({}) { |key_value, hash| | |
key, value = key_value | |
hash[key] = value + 1 | |
} | |
} | |
x.report("merge") { | |
MONDO_HASH.merge({}) { |key, value| value + 1 } | |
} | |
x.report("merge self") { | |
MONDO_HASH.merge(MONDO_HASH) { |key, value| value + 1 } | |
} | |
x.report("Hash[map]") { | |
Hash[MONDO_HASH.map { |key, value| [key, value + 1] }] | |
} | |
x.report("long form") { | |
hash = {} | |
MONDO_HASH.each { |key, value| | |
hash[key] = value + 1 | |
} | |
hash | |
} | |
x.report("map_values monkey patch") { | |
MONDO_HASH.map_values { |value| | |
value + 1 | |
} | |
} | |
x.compare! | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment