-
-
Save spraints/1795543 to your computer and use it in GitHub Desktop.
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
class Hash | |
def self.nmerge(*hashes, &block) | |
keys = hashes.map(&:keys).flatten.uniq | |
rhashes = hashes.reverse | |
keys.inject({ }) do |output, key| | |
if block | |
output[key] = block.call(key, hashes.map{ |x| x[key]}) | |
else | |
rhashes.each do |hash| | |
if hash[key] | |
output[key] = hash[key] | |
break | |
end | |
end | |
end | |
output | |
end | |
end | |
def self.mmerge(*hashes) | |
hashes.inject { |a,b| a.merge b } | |
end | |
def self.lmerge(*hashes) | |
hashes.inject({}) { |a,b| a.merge! b } | |
end | |
end | |
require 'benchmark' | |
one = {:one => 1, :two => 1} | |
two = {:two => 2, :three => 2} | |
three = {:three => 3, :four => 3} | |
puts Hash.nmerge(one, two, three).inspect | |
puts Hash.mmerge(one, two, three).inspect | |
puts Hash.lmerge(one, two, three).inspect | |
Benchmark.bmbm do |x| | |
x.report('nmerge') { 100000.times { Hash.nmerge one, two, three } } | |
x.report('mmerge') { 100000.times { Hash.mmerge one, two, three } } | |
x.report('lmerge') { 100000.times { Hash.lmerge one, two, three } } | |
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
>> ruby nm.rb | |
{:one=>1, :two=>2, :three=>3, :four=>3} | |
{:one=>1, :two=>2, :three=>3, :four=>3} | |
{:one=>1, :two=>2, :three=>3, :four=>3} | |
Rehearsal ------------------------------------------ | |
nmerge 1.220000 0.010000 1.230000 ( 1.254603) | |
mmerge 0.460000 0.000000 0.460000 ( 0.469838) | |
lmerge 0.260000 0.000000 0.260000 ( 0.259385) | |
--------------------------------- total: 1.950000sec | |
user system total real | |
nmerge 1.070000 0.000000 1.070000 ( 1.068250) | |
mmerge 0.440000 0.000000 0.440000 ( 0.443846) | |
lmerge 0.270000 0.010000 0.280000 ( 0.274417) | |
>> ruby -v | |
ruby 1.9.2p290 (2011-07-09 revision 32553) [x86_64-darwin10.8.0] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
nmerge 9.290000 0.020000 9.310000 ( 9.294319)
mmerge 5.330000 0.120000 5.450000 ( 5.450449)
lmerge 2.300000 0.020000 2.320000 ( 2.318999)