Created
December 2, 2016 18:00
-
-
Save guigs/ba34d5b88accae2531fefb7d78aa68f2 to your computer and use it in GitHub Desktop.
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 = 10_000 | |
def get_number | |
rand(1000) | |
end | |
def array | |
a = [] | |
SIZE.times do | |
n = get_number | |
a.push(n) unless a.include?(n) | |
end | |
end | |
def set | |
s = Set.new | |
SIZE.times do | |
n = get_number | |
s << n | |
end | |
end | |
def hash | |
h = Hash.new(0) | |
SIZE.times do | |
n = get_number | |
h[n] += 1 | |
end | |
end | |
def benchmark(x) | |
x.report("array: ") { array } | |
x.report("set: ") { set } | |
x.report("hash: ") { hash } | |
x.compare! | |
end | |
Benchmark.memory(&method(:benchmark)) | |
Benchmark.ips(&method(:benchmark)) | |
# Results | |
# Memory Comparison: | |
# array: : 11840 allocated | |
# hash: : 50136 allocated - 4.23x more | |
# set: : 50176 allocated - 4.24x more | |
# | |
# Speed Comparasion: | |
# set: : 276.3 i/s | |
# hash: : 275.7 i/s - same-ish: difference falls within error | |
# array: : 34.4 i/s - 8.04x slower |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment