Skip to content

Instantly share code, notes, and snippets.

@SamSaffron
Created September 11, 2013 00:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save SamSaffron/6517812 to your computer and use it in GitHub Desktop.
Save SamSaffron/6517812 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
@SamSaffron
Copy link
Author

                                          user     system      total        real
init with dup                         0.730000   0.000000   0.730000 (  0.743440)
init with hash                        0.380000   0.000000   0.380000 (  0.386889)
init with copy                        0.000000   0.000000   0.000000 (  0.006719)
init with dup with lookup             1.080000   0.000000   1.080000 (  1.085757)
init with hash with lookup            0.760000   0.000000   0.760000 (  0.768564)
init with copy with lookup            0.400000   0.000000   0.400000 (  0.407021)
init with copy with fallback lookup   0.410000   0.000000   0.410000 (  0.408564)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment