Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save dimameshcharakou/d772e94a7c4f8b6c4ce7106a6969df8c to your computer and use it in GitHub Desktop.
Save dimameshcharakou/d772e94a7c4f8b6c4ce7106a6969df8c to your computer and use it in GitHub Desktop.
hash fetch default vs block with no argument
require 'benchmark'
Benchmark.bm do |x|
x.report("fetch with block") do
1_000_000.times do
attrs = {}
attrs.fetch('xyz') { 'abc' }
end
end
x.report("fetch with default") do
1_000_000.times do
attrs = {}
attrs.fetch('xyz', 'abc')
end
end
end
# Results
# user system total real
# fetch with block 0.200000 0.000000 0.200000 ( 0.204277)
# fetch with default 0.160000 0.000000 0.160000 ( 0.155238)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment