Last active
September 19, 2016 11:47
-
-
Save denyago/2a39aa88fc4d7663025588dfafe4be51 to your computer and use it in GitHub Desktop.
Compare speed of key lookup using Hash, Set and Array.
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
require "benchmark/ips" | |
require "benchmark/memory" | |
require "set" | |
SIZE = 50 | |
def mk_key(i) | |
"key-#{i}" | |
end | |
def init_set(size) | |
memory = Set.new | |
size.times { |i| memory << mk_key(i) } | |
memory | |
end | |
def init_array(size) | |
memory = Array.new | |
size.times { |i| memory << mk_key(i) } | |
memory | |
end | |
def init_hash(size) | |
memory = Hash.new | |
size.times { |i| memory[mk_key(i)] = nil } | |
memory | |
end | |
def find_set_or_array(memory) | |
SIZE.times { |i| memory.include?(mk_key(i)) } | |
end | |
def find_hash(memory) | |
SIZE.times { |i| memory.key?(mk_key(i)) } | |
end | |
puts "SIZE = #{SIZE}\n" | |
Benchmark.ips do |x| | |
x.report("set") { find_set_or_array(init_set(SIZE)) } | |
x.report("array") { find_set_or_array(init_array(SIZE)) } | |
x.report("hash") { find_hash(init_hash(SIZE)) } | |
x.compare! | |
end | |
Benchmark.memory do |x| | |
x.report("set") { find_set_or_array(init_set(SIZE)) } | |
x.report("array") { find_set_or_array(init_array(SIZE)) } | |
x.report("hash") { find_hash(init_hash(SIZE)) } | |
x.compare! | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Results: