Skip to content

Instantly share code, notes, and snippets.

@jnicklas
Created August 30, 2012 23:04
Show Gist options
  • Save jnicklas/3544217 to your computer and use it in GitHub Desktop.
Save jnicklas/3544217 to your computer and use it in GitHub Desktop.
Hash access speed with strings/vs symbols
require "benchmark"
string_hash = {}
symbol_hash = {}
(0..50000).map do |i|
string_hash["key_#{i}"] = i
symbol_hash[:"key_#{i}"] = i
end
string_accessors = Array.new(100000) { "key_#{rand(50000)}" }
symbol_accessors = Array.new(100000) { :"key_#{rand(50000)}" }
Benchmark.bm do |x|
x.report("strings") { string_accessors.each { |a| string_hash[a] } }
x.report("symbols") { symbol_accessors.each { |a| symbol_hash[a] } }
x.report("strings, set") { string_accessors.each { |a| string_hash[a] = a } }
x.report("symbols, set") { symbol_accessors.each { |a| symbol_hash[a] = a } }
end
user system total real
strings 0.030000 0.000000 0.030000 ( 0.031394)
symbols 0.010000 0.000000 0.010000 ( 0.019276)
strings, set 0.040000 0.000000 0.040000 ( 0.036649)
symbols, set 0.030000 0.000000 0.030000 ( 0.024406)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment