Created
January 12, 2022 16:26
-
-
Save billthompson/380790749f0c8d30ec14d06cfa705705 to your computer and use it in GitHub Desktop.
Benchmarking Ruby's fetch against ActiveSupport's try.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 |
Author
billthompson
commented
Jan 12, 2022
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment