Last active
December 15, 2015 17:29
-
-
Save dbenhur/5296334 to your computer and use it in GitHub Desktop.
Micro bench for SO http://stackoverflow.com/questions/15771293/selecting-values-from-a-large-hash-based-on-a-large-array-in-ruby-is-slow
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
#!/usr/bin/env ruby | |
require 'set' | |
require 'benchmark' | |
N = 5 | |
HSZ = 150_000 | |
ASZ = 25_000 | |
HH = Hash[ (0...HSZ).map{|i| [i, 'something'] } ].freeze | |
A = (0...ASZ).map{ Random.rand(HSZ) }.freeze | |
S = A.to_set.freeze | |
# to account for the HH.dup cost reseting hash on each iteration. | |
def noop(h,a,s) | |
end | |
def keys_minus_arr_delete(h,a,s) | |
(h.keys - a).each{|k| h.delete(k)} | |
end | |
def select_set_include(h,a,s) | |
h.select{|k,_| s.include?(k) } | |
end | |
def select_set_include_fly(h,a,s) | |
s = a.to_set | |
h.select{|k,_| s.include?(k) } | |
end | |
def select_arr_include(h,a,s) | |
h.select{|k,_| a.include?(k) } | |
end | |
def sawa2(h,a,s) | |
keys_to_be_removed = {} | |
h.each{|k, _| keys_to_be_removed[k] = true} | |
a.each{|k| keys_to_be_removed[k] = false} | |
keys_to_be_removed.each{|k, v| h.delete(k) if v} | |
end | |
methods = [:noop, :keys_minus_arr_delete, :select_set_include, :select_set_include_fly, :sawa2 | |
# :select_arr_include, # takes too long | |
] | |
Benchmark.bm(25) do |x| | |
methods.each do |m| | |
x.report(m.to_s) { N.times{ send(m, HH.dup, A, S) } } | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment