Skip to content

Instantly share code, notes, and snippets.

@justincampbell
Created June 10, 2015 19:15
Show Gist options
  • Save justincampbell/00ec2b95b57b3332d5da to your computer and use it in GitHub Desktop.
Save justincampbell/00ec2b95b57b3332d5da to your computer and use it in GitHub Desktop.
require 'benchmark'
n = (ENV['N'] || 1_000_000).to_i
HASH = { foo: 1, bar: 2 }.freeze
Benchmark.bm(20) do |x|
x.report("case") do
n.times do
case :baz
when :foo then 1
when :bar then 2
end
end
end
x.report("hash lookup") do
n.times do
HASH[:foo]
end
end
x.report("hash fetch") do
n.times do
HASH.fetch(:foo)
end
end
x.report("hash fetch w/ default") do
n.times do
HASH.fetch(:baz, 3)
end
end
end
user system total real
case 0.060000 0.000000 0.060000 ( 0.059396)
hash lookup 0.060000 0.000000 0.060000 ( 0.060274)
hash fetch 0.090000 0.000000 0.090000 ( 0.081596)
hash fetch w/ default 0.080000 0.000000 0.080000 ( 0.086255)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment