Skip to content

Instantly share code, notes, and snippets.

@tiagoamaro
Last active September 2, 2024 15:36
Show Gist options
  • Select an option

  • Save tiagoamaro/c82a27aceedfc901b081 to your computer and use it in GitHub Desktop.

Select an option

Save tiagoamaro/c82a27aceedfc901b081 to your computer and use it in GitHub Desktop.
ActiveSupport's HashWithIndifferentAccess access benchmark vs common Ruby Hash
require 'active_support/all'
require 'benchmark/ips'
Benchmark.ips do |x|
x.config(time: 10, warmup: 5)
@hash_with_indifferent_access = ActiveSupport::HashWithIndifferentAccess.new(a: 1)
@hash = Hash[a: 2]
x.report("Common Hash#fetch access") do
@hash.fetch :a
end
x.report("Common Hash#[] access") do
@hash[:a]
end
x.report("HashWithIndifferentAccess#fetch Symbol") do
@hash_with_indifferent_access.fetch :a
end
x.report("HashWithIndifferentAccess#fetch String") do
@hash_with_indifferent_access.fetch 'a'
end
x.report("HashWithIndifferentAccess #[] Symbol") do
@hash_with_indifferent_access[:a]
end
x.report("HashWithIndifferentAccess #[] String") do
@hash_with_indifferent_access['a']
end
# Compare the iterations per second of the various reports!
x.compare!
end
# Results
# ▶ ruby hash_with_indifferent_access_benchmark.rb
# Calculating -------------------------------------
# Common Hash#fetch access
# 48.807k i/100ms
# Common Hash#[] access
# 49.208k i/100ms
# HashWithIndifferentAccess#fetch Symbol
# 41.106k i/100ms
# HashWithIndifferentAccess#fetch String
# 42.017k i/100ms
# HashWithIndifferentAccess #[] Symbol
# 38.126k i/100ms
# HashWithIndifferentAccess #[] String
# 47.241k i/100ms
# -------------------------------------------------
# Common Hash#fetch access
# 6.135M (±10.1%) i/s - 60.521M
# Common Hash#[] access
# 8.485M (± 9.3%) i/s - 83.850M
# HashWithIndifferentAccess#fetch Symbol
# 2.136M (± 7.4%) i/s - 21.252M
# HashWithIndifferentAccess#fetch String
# 2.183M (± 7.0%) i/s - 21.723M
# HashWithIndifferentAccess #[] Symbol
# 1.537M (± 7.2%) i/s - 15.289M
# HashWithIndifferentAccess #[] String
# 4.029M (± 8.2%) i/s - 39.966M
#
# Comparison:
# Common Hash#[] access: 8484846.1 i/s
# Common Hash#fetch access: 6135166.1 i/s - 1.38x slower
# HashWithIndifferentAccess #[] String: 4028542.5 i/s - 2.11x slower
# HashWithIndifferentAccess#fetch String: 2183267.0 i/s - 3.89x slower
# HashWithIndifferentAccess#fetch Symbol: 2136342.2 i/s - 3.97x slower
# HashWithIndifferentAccess #[] Symbol: 1536753.4 i/s - 5.52x slower
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment