Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Benchmarking a reimplementation of Hash#deep_merge from the ActiveSupport library
require 'active_support'
require 'benchmark/ips'
class Hash
def new_deep_merge(other_hash, &block)
dup.new_deep_merge!(other_hash, &block)
end
def new_deep_merge!(other, &block)
merge!(other) do |key, old_val, new_val|
if old_val.is_a?(Hash) && new_val.is_a?(Hash)
old_val.new_deep_merge(new_val, &block)
elsif block_given?
block.call(key, old_val, new_val)
else
new_val
end
end
end
end
h1 = { a: true, b: { c: [1, 2, 3] }, d: 1 }
h2 = { a: false, b: { c: [3, 4, 5] }, d: 2 }
h3 = { a: false, b: { x: [3, 4, 5] }, e: 2, f: { y: false } }
h4 = { e: 2, f: { y: false }, g: 'hi', h: true }
Benchmark.ips do |bm|
bm.report('old_deep_merge_all_dupes') { h1.deep_merge(h2) }
bm.report('new_deep_merge_all_dupes') { h1.new_deep_merge(h2) }
bm.compare!
end
Benchmark.ips do |bm|
bm.report('old_deep_merge_some_dupes') { h1.deep_merge(h3) }
bm.report('new_deep_merge_some_dupes') { h1.new_deep_merge(h3) }
bm.compare!
end
Benchmark.ips do |bm|
bm.report('old_deep_merge_no_dupes') { h1.deep_merge(h4) }
bm.report('new_deep_merge_no_dupes') { h1.new_deep_merge(h4) }
bm.compare!
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment