Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save marcreynolds/7d6ad0a12118a1a8219bdcb38ba23150 to your computer and use it in GitHub Desktop.
Save marcreynolds/7d6ad0a12118a1a8219bdcb38ba23150 to your computer and use it in GitHub Desktop.
require "benchmark/ips"
puts "when the key is in the hash"
Benchmark.ips do |x|
h = { foo: :bar }
x.report("dig with single parameter") do
h.dig(:foo)
end
x.report("fetch with single parameter") do
h.fetch(:foo)
end
x.report("#[]") do
h[:foo]
end
x.compare!
end
puts "when the key isn't in the hash"
Benchmark.ips() do |x|
h = { foo: :bar }
x.report("dig with single parameter") do
h.dig(:baz)
end
x.report("fetch with single parameter") do
h.fetch(:baz, nil)
end
x.report("#[]") do
h[:baz]
end
x.compare!
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment