Skip to content

Instantly share code, notes, and snippets.

@hassox
Forked from jnicklas/benchmark.rb
Created August 30, 2012 23:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hassox/3544925 to your computer and use it in GitHub Desktop.
Save hassox/3544925 to your computer and use it in GitHub Desktop.
Hash access speed with strings/vs symbols
require "benchmark"
hash = {'key' => 1, :key => 2}
n = 5_000_000
Benchmark.bm do |x|
x.report("strings") { n.times { hash['key'] } }
x.report("symbols") { n.times { hash[:key] } }
x.report("strings, set") { n.times { hash['key'] = 1 } }
x.report("symbols, set") { n.times { hash[:key] = 1 } }
end
user system total real
strings 1.040000 0.010000 1.050000 ( 1.044701)
symbols 0.460000 0.000000 0.460000 ( 0.461030)
strings, set 1.250000 0.000000 1.250000 ( 1.253017)
symbols, set 0.690000 0.000000 0.690000 ( 0.689607)
@jwreagor
Copy link

jwreagor commented Sep 1, 2012

I think removing the hash ops speaks for itself. It's all about the string allocation and symbol table searching.

Benchmark.bm do |x|
  x.report("strings") { n.times { 'key' } }
  x.report("symbols") { n.times { :key } }
end

user system total real
strings 1.170000 0.000000 1.170000 ( 1.172716)
symbols 0.310000 0.000000 0.310000 ( 0.316076)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment