Skip to content

Instantly share code, notes, and snippets.

@tenderlove
Forked from SamSaffron/the_dup_cost.rb
Created September 11, 2013 00:32
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 tenderlove/6517832 to your computer and use it in GitHub Desktop.
Save tenderlove/6517832 to your computer and use it in GitHub Desktop.
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