Created
April 7, 2012 21:19
-
-
Save copiousfreetime/2332161 to your computer and use it in GitHub Desktop.
hash like comparison benchmark
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
#!/usr/bin/env ruby | |
require 'rubygems' | |
require "benchmark" | |
require 'map' | |
require 'digest/md5' | |
require 'hashr' | |
require 'hashie' | |
def keys( count, start = 'aaaaaa' ) | |
k = [] | |
count.times { k << start.succ! } | |
return k | |
end | |
def values_from( keys1, keys2 ) | |
values = [] | |
keys1.each do |k1| | |
keys2.each do |k2| | |
values << Digest::MD5.hexdigest( "#{k1}/#{k2}" ) | |
end | |
end | |
return values | |
end | |
def nested_yield( keys1, keys2 ) | |
keys1.each do |k1| | |
keys2.each do |k2| | |
yield k1, k2 | |
end | |
end | |
end | |
puts "Testing 2 level hashes between Hash and Map" | |
keys1 = keys( 100, 'aaaaaa' ) | |
keys2 = keys( 100, 'bbbbbb' ) | |
puts "Starting benchmark" | |
Benchmark.bm(42) do |bm| | |
bm.report("values gen") do | |
values = values_from( keys1, keys2 ) | |
end | |
bm.report("Hash") do | |
h = Hash.new{ |h,k| h[k] = Hash.new } | |
values = values_from( keys1, keys2 ) | |
nested_yield( keys1, keys2) do |k1, k2| | |
h[k1][k2] = values.shift | |
end | |
end | |
bm.report("Map.set") do | |
m = Map.new | |
values = values_from( keys1, keys2 ) | |
nested_yield( keys1, keys2 ) do |k1, k2| | |
m.set( k1, k2, values.shift ) | |
end | |
end | |
bm.report( "Hashr" ) do | |
h = Hashr.new | |
values = values_from( keys1, keys2 ) | |
nested_yield( keys1, keys2 ) do |k1, k2| | |
h.set("#{k1}.#{k2}", values.shift ) | |
end | |
end | |
bm.report( "Mash" ) do | |
m = Hashie::Mash.new | |
values = values_from( keys1, keys2 ) | |
nested_yield( keys1, keys2 ) do |k1, k2| | |
m.send( "#{k1}!" ).send( "#{k2}=", values.shift ) | |
end | |
end | |
end | |
__END__ | |
% ruby hashlike_bench.rb | |
Testing 2 level hashes between Hash and Map | |
Starting benchmark | |
user system total real | |
values gen 0.030000 0.000000 0.030000 ( 0.028457) | |
Hash 0.040000 0.000000 0.040000 ( 0.040128) | |
Map.set 0.260000 0.010000 0.270000 ( 0.258244) | |
Hashr 0.450000 0.010000 0.460000 ( 0.473694) | |
Mash 0.180000 0.010000 0.190000 ( 0.178579) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment