require "benchmark/ips"
MY_HASH = (1..99).each_with_object({}) { |n,h| h[n.to_s] = n }
def fast
MY_HASH.fetch('nope') { 'default' }
end
def slow
MY_HASH.fetch 'nope', 'default'
end
Benchmark.ips do |x|
x.report("Hash#fetch with block") { fast }
x.report("Hash#fetch with second argument") { slow }
x.compare!
end
Ruby 2.5.7
Warming up --------------------------------------
Hash#fetch with block
288.905k i/100ms
Hash#fetch with second argument
315.096k i/100ms
Calculating -------------------------------------
Hash#fetch with block
5.247M (± 0.7%) i/s - 26.290M in 5.011189s
Hash#fetch with second argument
6.183M (± 5.2%) i/s - 30.879M in 5.009613s
Comparison:
Hash#fetch with second argument: 6182898.3 i/s
Hash#fetch with block: 5246593.2 i/s - 1.18x slower
Ruby 2.7.0
Warming up --------------------------------------
Hash#fetch with block
328.574k i/100ms
Hash#fetch with second argument
394.964k i/100ms
Calculating -------------------------------------
Hash#fetch with block
6.444M (± 1.1%) i/s - 32.529M in 5.048419s
Hash#fetch with second argument
8.438M (± 0.6%) i/s - 42.261M in 5.008428s
Comparison:
Hash#fetch with second argument: 8438304.4 i/s
Hash#fetch with block: 6444222.1 i/s - 1.31x slower
Ruby 2.5.7
Ruby 2.7.0