Skip to content

Instantly share code, notes, and snippets.

@beanieboi
Last active August 29, 2015 14:06
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 beanieboi/732a8c16144332e26479 to your computer and use it in GitHub Desktop.
Save beanieboi/732a8c16144332e26479 to your computer and use it in GitHub Desktop.
Benchmarking fetch vs [] in Ruby
Calculating -------------------------------------
hash containing key using fetch with block
                         56342 i/100ms
hash containing key using [] with ||
                         63758 i/100ms
-------------------------------------------------
hash containing key using fetch with block
                      1600812.5 (±25.4%) i/s -    6592014 in   5.013939s
hash containing key using [] with ||
                      1840451.4 (±27.3%) i/s -    7395928 in   5.023841s

Comparison:
hash containing key using [] with ||:  1840451.4 i/s
hash containing key using fetch with block:  1600812.5 i/s - 1.15x slower

Calculating -------------------------------------
hash doesn't contain key using fetch with block
                         12404 i/100ms
hash doesn't contain key using  [] with ||
                         12633 i/100ms
-------------------------------------------------
hash doesn't contain key using fetch with block
                       154065.8 (±15.7%) i/s -     744240 in   5.016155s
hash doesn't contain key using  [] with ||
                       162945.7 (±15.7%) i/s -     795879 in   5.067547s

Comparison:
hash doesn't contain key using  [] with ||:   162945.7 i/s
hash doesn't contain key using fetch with block:   154065.8 i/s - 1.06x slower

Benchmarking Code:

require 'bundler'

Bundler.require

Benchmark.ips do |x|
  x.report("hash containing key using fetch with block") do
    { foo: :bar }.fetch(:foo) { (1..100).to_a }
  end

  x.report("hash containing key using [] with ||") do
    { foo: :bar }[:foo] || (1..100).to_a
  end

  x.compare!
end

Benchmark.ips do |x|
  x.report("hash doesn't contain key using fetch with block") do
    { foo: :bar }.fetch(:foobar) { (1..100).to_a }
  end

  x.report("hash doesn't contain key using  [] with ||") do
    { foo: :bar }[:foobar] || (1..100).to_a
  end

  x.compare!
end


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