Skip to content

Instantly share code, notes, and snippets.

@dbenhur
Last active December 15, 2015 17:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dbenhur/5296334 to your computer and use it in GitHub Desktop.
Save dbenhur/5296334 to your computer and use it in GitHub Desktop.
#!/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