Skip to content

Instantly share code, notes, and snippets.

@guigs
Created December 2, 2016 18:00
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 guigs/ba34d5b88accae2531fefb7d78aa68f2 to your computer and use it in GitHub Desktop.
Save guigs/ba34d5b88accae2531fefb7d78aa68f2 to your computer and use it in GitHub Desktop.
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