From: Trans Date: 2006-12-27T08:34:39+09:00 Subject: Re: Hash with two identical keys? William James wrote: > Here's a speed comparison for various numbers of keys: > > require 'benchmark' > > $iterations = 40_000 > > def rand_sym > letters = ('a'..'z').to_a > sym = "" > 8.times{ sym << letters[ rand(letters.size) ] } > sym.to_sym > end > > def test_assoc n > alist = [] > keys = [] > while alist.size < n do > key = rand_sym > unless keys.include?( key ) > alist << [ key, true ] > keys << key > end > end > $iterations.times{ > keys.each{|key| fail if alist.assoc(key)[1] != true } > } > end > > def test_hash n > hash = {} > keys = [] > while hash.size < n > key = rand_sym > unless hash.include?( key ) > hash[key] = true > keys << key > end > end > $iterations.times{ > keys.each{|key| fail if hash[key] != true } > } > end > > Benchmark.bm(8) do |x| > [1,2,3,7,20].each{ |n| > x.report("assoc %2d" % n) { test_assoc n } > x.report("hash %2d" % n) { test_hash n } > } > end > > user system total real > assoc 1 0.150000 0.000000 0.150000 ( 0.171000) > hash 1 0.130000 0.000000 0.130000 ( 0.140000) > assoc 2 0.291000 0.000000 0.291000 ( 0.310000) > hash 2 0.200000 0.000000 0.200000 ( 0.231000) > assoc 3 0.440000 0.000000 0.440000 ( 0.460000) > hash 3 0.291000 0.000000 0.291000 ( 0.311000) > assoc 7 1.172000 0.000000 1.172000 ( 1.252000) > hash 7 0.590000 0.000000 0.590000 ( 0.640000) > assoc 20 5.188000 0.000000 5.188000 ( 5.578000) > hash 20 1.652000 0.000000 1.652000 ( 1.813000) Nice. Doesn't matter a whole lot a few keys but there is a clear slow down. I came up with another possibility however. I won;t work for all cases, but using Marshal.dup on the args instead of converting to assoc gives the proper result too. Wonder how that would benchmark? T.