Skip to content

Instantly share code, notes, and snippets.

@carlosantoniodasilva
Created January 9, 2013 15:56
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 carlosantoniodasilva/4494229 to your computer and use it in GitHub Desktop.
Save carlosantoniodasilva/4494229 to your computer and use it in GitHub Desktop.
Benchmarck Hash#[] vs Hash#fetch
require 'benchmark'
TIMES = 100000
HASH = { as: :fuu }
Benchmark.bm(25) do |x|
x.report('[:as] (existing)') do
TIMES.times do
HASH[:as] || :default
end
end
x.report('[:as] (non existing)') do
TIMES.times do
HASH[:ax] || :default
end
end
x.report('fetch(:as) (existing)') do
TIMES.times do
HASH.fetch(:as, :default)
end
end
x.report('fetch(:as) (non existing)') do
TIMES.times do
HASH.fetch(:ax, :default)
end
end
x.report('fetch(:as) {} (existing)') do
TIMES.times do
HASH.fetch(:as) { :default }
end
end
x.report('fetch(:as) {} (non existing)') do
TIMES.times do
HASH.fetch(:ax) { :default }
end
end
end
require 'benchmark/ips'
Benchmark.ips do |x|
x.report('[:as] (existing)') do
HASH[:as] || :default
end
x.report('[:as] (non existing)') do
HASH[:ax] || :default
end
x.report('fetch(:as) (existing)') do
HASH.fetch(:as, :default)
end
x.report('fetch(:as) (non existing)') do
HASH.fetch(:ax, :default)
end
x.report('fetch(:as) {} (existing)') do
HASH.fetch(:as) { :default }
end
x.report('fetch(:as) {} (non existing)') do
HASH.fetch(:ax) { :default }
end
end
=begin
# BM
user system total real
[:as] (existing) 0.000000 0.000000 0.000000 ( 0.008880)
[:as] (non existing) 0.020000 0.000000 0.020000 ( 0.012835)
fetch(:as) (existing) 0.020000 0.000000 0.020000 ( 0.020105)
fetch(:as) (non existing) 0.010000 0.000000 0.010000 ( 0.014273)
fetch(:as) {} (existing) 0.020000 0.000000 0.020000 ( 0.016462)
fetch(:as) {} (non existing) 0.030000 0.000000 0.030000 ( 0.028847)
# IPS
Calculating -------------------------------------
[:as] (existing) 86313 i/100ms
[:as] (non existing) 85304 i/100ms
fetch(:as) (existing) 76593 i/100ms
fetch(:as) (non existing) 62863 i/100ms
fetch(:as) {} (existing) 74604 i/100ms
fetch(:as) {} (non existing) 71734 i/100ms
-------------------------------------------------
[:as] (existing) 5604410.9 (±8.7%) i/s - 27792786 in 5.009524s
[:as] (non existing) 4877521.6 (±9.8%) i/s - 24141032 in 5.008405s
fetch(:as) (existing) 3729943.1 (±5.2%) i/s - 18612099 in 5.005361s
fetch(:as) (non existing) 3708001.5 (±7.5%) i/s - 18418859 in 5.001811s
fetch(:as) {} (existing) 3721445.4 (±7.2%) i/s - 18501792 in 5.001294s
fetch(:as) {} (non existing) 2900120.0 (±5.5%) i/s - 14490268 in 5.014043s
=end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment