Hash With Indifferent Access vs to_s vs. to_sym benchmark
require 'benchmark/ips'
Benchmark.ips do |b|
hash = {}
strings = Array.new(1000){('a'..'z').to_a.shuffle[0,15].join}
symbols = strings.map &:to_sym
index = nil
require 'active_support/core_ext/hash/indifferent_access'
b.report("strings to_sym in and out") do
index = strings.sample
hash[index.to_sym] = 'sample'
hash[index.to_sym]
end
hash = {}
b.report("symbols to_s in and out") do
index = symbols.sample
hash[index.to_s] = 'sample'
hash[index.to_s]
end
hash = {}
b.report("strings to_s in and out") do
index = strings.sample
hash[index.to_s] = 'sample'
hash[index.to_s]
end
hash = {}.with_indifferent_access
b.report("HWIA with string keys in and out") do
index = strings.sample
hash[index] = 'sample'
hash[index]
end
hash = {}.with_indifferent_access
b.report("HWIA with symbol keys in and out") do
index = symbols.sample
hash[index] = 'sample'
hash[index]
end
hash = {}.with_indifferent_access
b.report("HWIA with symbols to_s string keys in and out") do
index = symbols.sample
hash[index.to_s] = 'sample'
hash[index.to_s]
end
b.compare!
end
Warming up --------------------------------------
strings to_sym in and out
30.830k i/100ms
symbols to_s in and out
43.916k i/100ms
strings to_s in and out
45.556k i/100ms
HWIA with string keys in and out
47.254k i/100ms
HWIA with symbol keys in and out
35.100k i/100ms
HWIA with symbols to_s string keys in and out
42.988k i/100ms
Calculating -------------------------------------
strings to_sym in and out
404.463k (± 4.2%) i/s - 2.035M
symbols to_s in and out
622.900k (± 3.9%) i/s - 3.118M
strings to_s in and out
690.458k (± 5.0%) i/s - 3.462M
HWIA with string keys in and out
723.858k (± 4.7%) i/s - 3.639M
HWIA with symbol keys in and out
469.217k (± 4.0%) i/s - 2.352M
HWIA with symbols to_s string keys in and out
634.770k (± 4.1%) i/s - 3.181M
Comparison:
HWIA with string keys in and out: 723858.3 i/s
strings to_s in and out: 690457.5 i/s - same-ish: difference falls within error
HWIA with symbols to_s string keys in and out: 634769.8 i/s - 1.14x slower
symbols to_s in and out: 622900.4 i/s - 1.16x slower
HWIA with symbol keys in and out: 469216.5 i/s - 1.54x slower
strings to_sym in and out: 404462.7 i/s - 1.79x slower