Skip to content

Instantly share code, notes, and snippets.

@JonRowe
Created August 20, 2013 11:35
Show Gist options
  • Save JonRowe/6280298 to your computer and use it in GitHub Desktop.
Save JonRowe/6280298 to your computer and use it in GitHub Desktop.
Hash key lookup performance vs local variable.
require 'benchmark'
require 'stringio'
sizes = [10,100,1000,10000]
def measure(&block)
puts Benchmark.measure { 100000.times(&block) }
end
sizes.each do |size|
fake_io = StringIO.new
other_fake_io = StringIO.new
hash = (1..size).inject({}) { |h, k| h[k] = "value #{k}"; h }
puts "Measuring for hash size #{size}"
puts "Key lookup"
measure do
5.times { fake_io.puts hash[5] }
end
puts "Var stash"
measure do
var = hash[5]
5.times { other_fake_io.puts var }
end
end
Measuring for hash size 10
Key lookup
0.310000 0.010000 0.320000 ( 0.310216)
Var stash
0.290000 0.000000 0.290000 ( 0.294578)
Measuring for hash size 100
Key lookup
0.320000 0.000000 0.320000 ( 0.319517)
Var stash
0.310000 0.010000 0.320000 ( 0.317231)
Measuring for hash size 1000
Key lookup
0.310000 0.000000 0.310000 ( 0.315608)
Var stash
0.300000 0.010000 0.310000 ( 0.303324)
Measuring for hash size 10000
Key lookup
0.390000 0.000000 0.390000 ( 0.412032)
Var stash
0.320000 0.010000 0.330000 ( 0.326415)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment