Skip to content

Instantly share code, notes, and snippets.

@cjbottaro
Created January 14, 2016 20:45
Show Gist options
  • Save cjbottaro/54ffd5a596d0980be703 to your computer and use it in GitHub Desktop.
Save cjbottaro/54ffd5a596d0980be703 to your computer and use it in GitHub Desktop.
Optimize lookups with Hash
require "benchmark"
def slow(list1, list2)
count = 0
list1.each do |n|
count += 1 if list2.include?(n)
end
count
end
def fast(list1, list2)
# Convert list2 into a Hash
hash2 = {}
list2.each{ |n| hash2[n] = true }
count = 0
list1.each do |n|
count += 1 if hash2.include?(n)
end
count
end
list_a = 1_000.times.map{ rand(1_000) }
list_b = 1_000_000.times.map{ rand(1_000_000) }
puts Benchmark.realtime{ slow(list_a, list_b) }
puts Benchmark.realtime{ fast(list_a, list_b) }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment