Skip to content

Instantly share code, notes, and snippets.

@billthompson
Created January 12, 2022 16:26
Show Gist options
  • Save billthompson/380790749f0c8d30ec14d06cfa705705 to your computer and use it in GitHub Desktop.
Save billthompson/380790749f0c8d30ec14d06cfa705705 to your computer and use it in GitHub Desktop.
Benchmarking Ruby's fetch against ActiveSupport's try.
#!/usr/bin/env ruby
# frozen_string_literal: true
require 'benchmark'
require 'active_support/core_ext/object/try'
n = 5000000
puts "Key not found:"
sad_hash = {}
Benchmark.bm(7) do |x|
x.report("try") { n.times { sad_hash.try(:[], :test) } }
x.report("fetch") { n.times { sad_hash.fetch(:test, nil) } }
end
puts "\n---\n\n"
puts "Key found:"
happy_hash = { test: true }
Benchmark.bm(7) do |x|
x.report("try") { n.times { happy_hash.try(:[], :test) } }
x.report("fetch") { n.times { happy_hash.fetch(:test) } }
end
@billthompson
Copy link
Author

$ ./ruby_try_vs_fetch_benchmark.rb
Key not found:
              user     system      total        real
try       1.083426   0.021701   1.105127 (  1.105285)
fetch     0.195870   0.003290   0.199160 (  0.199291)

---

Key found:
              user     system      total        real
try       1.077929   0.014164   1.092093 (  1.092481)
fetch     0.194351   0.002286   0.196637 (  0.196766)

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