Project

General

Profile

Feature #4801 ยป bm.rb

Benchmark comparing hash and string keys for hashes with various hit rates - drbrain (Eric Hodel), 08/16/2011 03:18 AM

 
require 'benchmark'

string_hash = {}
symbol_hash = {}

string_keys = ('aaaaa'..'aaaaj').to_a

symbol_keys = string_keys.map { |key| key.to_sym }

string_keys.each_with_index do |key, index| string_hash[key] = index end
symbol_keys.each_with_index do |key, index| string_hash[key] = index end

test_string_keys = string_keys # 100% hit rate
test_symbol_keys = symbol_keys

TIMES = 500_000

puts '100% hit rate'
Benchmark.bm 24 do |bm|
bm.report 'string hash, string keys' do
TIMES.times do
test_string_keys.each do |key|
string_hash[key]
end
end
end

bm.report 'string hash, symbol keys' do
TIMES.times do
test_symbol_keys.each do |key|
string_hash[key.to_s]
end
end
end

bm.report 'symbol hash, string keys' do
TIMES.times do
test_string_keys.each do |key|
symbol_hash[key.to_sym]
end
end
end

bm.report 'symbol hash, symbol keys' do
TIMES.times do
test_symbol_keys.each do |key|
symbol_hash[key]
end
end
end
end

test_string_keys = ('aaaaa'..'aaaat').to_a # 50% hit rate
test_symbol_keys = test_string_keys.map do |key| key.to_sym end

puts ' 50% hit rate'
Benchmark.bm 24 do |bm|
bm.report 'string hash, string keys' do
TIMES.times do
test_string_keys.each do |key|
string_hash[key]
end
end
end

bm.report 'string hash, symbol keys' do
TIMES.times do
test_symbol_keys.each do |key|
string_hash[key.to_s]
end
end
end

bm.report 'symbol hash, string keys' do
TIMES.times do
test_string_keys.each do |key|
symbol_hash[key.to_sym]
end
end
end

bm.report 'symbol hash, symbol keys' do
TIMES.times do
test_symbol_keys.each do |key|
symbol_hash[key]
end
end
end
end

test_string_keys = ('aaaaa'..'aaazz').to_a # 1.5% hit rate
test_symbol_keys = test_string_keys.map do |key| key.to_sym end

puts '1.4% hit rate'
Benchmark.bm 24 do |bm|
bm.report 'string hash, string keys' do
TIMES.times do
test_string_keys.each do |key|
string_hash[key]
end
end
end

bm.report 'string hash, symbol keys' do
TIMES.times do
test_symbol_keys.each do |key|
string_hash[key.to_s]
end
end
end

bm.report 'symbol hash, string keys' do
TIMES.times do
test_string_keys.each do |key|
symbol_hash[key.to_sym]
end
end
end

bm.report 'symbol hash, symbol keys' do
TIMES.times do
test_symbol_keys.each do |key|
symbol_hash[key]
end
end
end
end

    (1-1/1)