Created
December 6, 2017 07:19
-
-
Save yurikoval/e7136d06e73757a7fea07a175573d610 to your computer and use it in GitHub Desktop.
Finding an element using array/hash/set
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 'benchmark' | |
require 'active_support' | |
require 'active_support/all' | |
require 'set' | |
BENCHMARK_TIMES = 1_000_000 | |
def find_array(array, find_me) | |
array.any?{ |id, sku| id == find_me && sku.present? } | |
end | |
def find_hash(hash, find_me) | |
hash[find_me].present? | |
end | |
def find_set(set, find_me) | |
set.any?{ |id, sku| id == find_me && sku.present? } | |
end | |
array = 1000.times.map do |id| | |
[id, "sku_#{id}"] | |
end.shuffle | |
hash = array.to_h | |
set = array.to_set | |
find_me = array.sample.first | |
puts "Benchmarking Array" | |
puts Benchmark.measure { BENCHMARK_TIMES.times { find_array(array, find_me) } } | |
puts "Benchmarking Hash" | |
puts Benchmark.measure { BENCHMARK_TIMES.times { find_hash(hash, find_me) } } | |
puts "Benchmarking Set" | |
puts Benchmark.measure { BENCHMARK_TIMES.times { find_set(set, find_me) } } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment