Skip to content

Instantly share code, notes, and snippets.

@ndemianc
Last active June 25, 2018 21:17
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 ndemianc/c406b23fa61169f4bce7b6bc99f95221 to your computer and use it in GitHub Desktop.
Save ndemianc/c406b23fa61169f4bce7b6bc99f95221 to your computer and use it in GitHub Desktop.
Hash#dig vs Hash#fetch
require "benchmark"
h = { a: { b: { c: { d: { e: "foo" } } } } }
n = 50_000
Benchmark.bmbm(7) do |x|
x.report "Hash#dig" do
n.times do ; h.dig(:a, :b, :c, :d, :e); end
end
x.report "Hash#[]" do
n.times do ; h[:a][:b][:c][:d][:e]; end
end
x.report "Hash#[] ||" do
n.times do ; ((((h[:a] || {})[:b] || {})[:c] || {})[:d] || {})[:e]; end
end
x.report "Hash#[] &&" do
n.times do ; h[:a] && h[:a][:b] && h[:a][:b][:c] && h[:a][:b][:c][:d] && h[:a][:b][:c][:d][:e]; end
end
x.report "Hash#fetch" do
n.times do ; h.fetch(:a).fetch(:b).fetch(:c).fetch(:d).fetch(:e); end
end
x.report "Hash#fetch fallback" do
n.times do ; h.fetch(:a, {}).fetch(:b, {}).fetch(:c, {}).fetch(:d, {}).fetch(:e, nil); end
end
end
# Ruby 2.5.1 Results:
#
# Rehearsal -------------------------------------------------------
# Hash#dig 0.008549 0.000020 0.008569 ( 0.008586)
# Hash#[] 0.007598 0.000032 0.007630 ( 0.007665)
# Hash#[] || 0.008968 0.000049 0.009017 ( 0.010046)
# Hash#[] && 0.021017 0.000816 0.021833 ( 0.023432)
# Hash#fetch 0.012320 0.001342 0.013662 ( 0.013821)
# Hash#fetch fallback 0.020859 0.000659 0.021518 ( 0.022696)
# ---------------------------------------------- total: 0.082229sec
#
# user system total real
# Hash#dig 0.008722 0.000156 0.008878 ( 0.009031)
# Hash#[] 0.007424 0.000011 0.007435 ( 0.007443)
# Hash#[] || 0.008770 0.000074 0.008844 ( 0.009877)
# Hash#[] && 0.020502 0.000845 0.021347 ( 0.022503)
# Hash#fetch 0.011854 0.000044 0.011898 ( 0.012864)
# Hash#fetch fallback 0.018482 0.000767 0.019249 ( 0.020280)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment