-
-
Save raggi/131854 to your computer and use it in GitHub Desktop.
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" | |
class Hash | |
# Performs the opposite of <tt>merge</tt>, with the keys and values from the first hash taking precedence over the second. | |
def reverse_merge(other_hash) | |
other_hash.merge(self) | |
end | |
# Performs the opposite of <tt>merge</tt>, with the keys and values from the first hash taking precedence over the second. | |
# Modifies the receiver in place. | |
def reverse_merge!(other_hash) | |
replace(reverse_merge(other_hash)) | |
end | |
end | |
def hash1 | |
Hash[*%w(a b c d e).zip([1,2,3,4,5]).flatten] | |
end | |
def hash2 | |
Hash[*%w(a b c d e f).zip([10,20,30,40,50,60]).flatten] | |
end | |
TESTS = 10_000 | |
Benchmark.bmbm do |results| | |
results.report("revmerge:") { TESTS.times { hash1.reverse_merge!(hash2) } } | |
results.report("blomerge:") { TESTS.times { hash1.merge!(hash2) { |h,v1,v2| v1 } } } | |
end |
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 'rubygems' | |
require 'active_support' | |
require "rbench" | |
class Hash | |
def fast_reverse_merge( other_hash ) | |
self.merge( other_hash ){|k,o,n| o } | |
end | |
def fast_reverse_merge!( other_hash ) | |
self.merge!( other_hash ){|k,o,n| o } | |
end | |
end | |
first = { :one => 1, :two => 2 } | |
second = { :three => 3, :four => 4 } | |
RBench.run(10_000) do | |
report "Hash#reverse_merge!" do | |
first.reverse_merge!( second ) | |
end | |
report "Hash#fast_reverse_merge!" do | |
first.fast_reverse_merge!( second ) | |
end | |
report "Hash#reverse_merge" do | |
first.reverse_merge( second ) | |
end | |
report "Hash#fast_reverse_merge" do | |
first.fast_reverse_merge( second ) | |
end | |
end | |
=begin | |
Results | | |
------------------------------------------ | |
Hash#reverse_merge! 0.035 | | |
Hash#fast_reverse_merge! 0.018 | | |
Hash#reverse_merge 0.020 | | |
Hash#fast_reverse_merge 0.031 | | |
=end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment