Skip to content

Instantly share code, notes, and snippets.

@sikachu
Last active August 29, 2015 14:14
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 sikachu/5253f9df4e28836b8813 to your computer and use it in GitHub Desktop.
Save sikachu/5253f9df4e28836b8813 to your computer and use it in GitHub Desktop.
Fetch vs []
require "benchmark/ips"
hash = Hash.new
Benchmark.ips do |x|
x.report("fetch") { x = hash.fetch(:foo, "bar") }
x.report("fetch block") { x = hash.fetch(:foo) { "bar" } }
x.report("[]") { x = hash[:foo] || "bar" }
end
[~] ruby test.rb
Calculating -------------------------------------
fetch 112.887k i/100ms
fetch block 100.862k i/100ms
[] 117.423k i/100ms
-------------------------------------------------
fetch 4.399M (± 5.7%) i/s - 22.013M
fetch block 3.259M (± 5.8%) i/s - 16.239M
[] 5.079M (± 6.0%) i/s - 25.363M
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment