Skip to content

Instantly share code, notes, and snippets.

@jrunning
Last active August 16, 2016 14:57
Show Gist options
  • Save jrunning/1eddc4133bdfd52e382b6aea7d257c4e to your computer and use it in GitHub Desktop.
Save jrunning/1eddc4133bdfd52e382b6aea7d257c4e to your computer and use it in GitHub Desktop.
Is Ruby hash lookup faster with symbol keys than string keys?
require "benchmark/ips"
require "securerandom"
sym_hash = {}
str_hash = {}
1000.times do |i|
# Generate a random key between 3 and 32 characters long
SecureRandom.hex[0,rand(3..32)].tap do |key|
str_hash[key] = i
sym_hash[key.to_sym] = i
end
end
sym_lookup = sym_hash.keys.shuffle
str_lookup = str_hash.keys.shuffle
Benchmark.ips do |x|
x.report("symbol") {
sym_lookup.each {|key| sym_hash[key] }
}
x.report("string") {
str_lookup.each {|key| str_hash[key] }
}
x.compare!
end
$ ruby -v
ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-darwin15]
$ ruby sym_vs_str.rb
Warming up --------------------------------------
symbol 1.139k i/100ms
string 752.000 i/100ms
Calculating -------------------------------------
symbol 11.590k (± 3.9%) i/s - 58.089k in 5.019694s
string 7.632k (± 3.7%) i/s - 38.352k in 5.031788s
Comparison:
symbol: 11589.9 i/s
string: 7632.3 i/s - 1.52x slower
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment