Skip to content

Instantly share code, notes, and snippets.

@yurikoval
Created December 6, 2017 07:19
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 yurikoval/e7136d06e73757a7fea07a175573d610 to your computer and use it in GitHub Desktop.
Save yurikoval/e7136d06e73757a7fea07a175573d610 to your computer and use it in GitHub Desktop.
Finding an element using array/hash/set
#!/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