Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
require 'benchmark'
class Tester
attr_accessor :hash
HASH = Hash[*(1..100).to_a]
def init_with_dup
@hash = HASH.dup
end
def init_with_hash
@hash = Hash[HASH]
end
def init_with_copy
@hash = HASH
end
def look_all_up
50.times{|i| @hash[i]}
end
def look_all_up_with_fallback
@bla = nil
50.times{|i| @bla[i] if @bla; @hash[i]}
end
end
@iterations = 100_000
@tester = Tester.new
Benchmark.bmbm do |x|
x.report("init with dup") do
@iterations.times{@tester.init_with_dup}
end
x.report("init with hash") do
@iterations.times{@tester.init_with_hash}
end
x.report("init with copy") do
@iterations.times{@tester.init_with_copy}
end
x.report("init with dup with lookup") do
@iterations.times{@tester.init_with_dup; @tester.look_all_up}
end
x.report("init with hash with lookup") do
@iterations.times{@tester.init_with_hash; @tester.look_all_up}
end
x.report("init with copy with lookup") do
@iterations.times{@tester.init_with_copy; @tester.look_all_up}
end
x.report("init with copy with fallback lookup") do
@iterations.times{@tester.init_with_copy; @tester.look_all_up_with_fallback}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment