Skip to content

Instantly share code, notes, and snippets.

@kalmanh
Created May 22, 2014 14:01
Show Gist options
  • Save kalmanh/7a9880b5fefa2b9b2cef to your computer and use it in GitHub Desktop.
Save kalmanh/7a9880b5fefa2b9b2cef to your computer and use it in GitHub Desktop.
Using symbols as keys in hash vs. strings
require 'benchmark'
NUM_TIMES = 100000000
ARR = (5000..10000).to_a
hash1 = {}
strings = %w{"Lorem ipsum bla abra kadabra"}
strings.each do |str|
hash1[str] = ARR.sample
end
hash2 = {}
symbols = [:Lorem, :ipsum, :bla, :abra, :kadabra]
symbols.each do |symbol|
hash2[symbol] = ARR.sample
end
Benchmark.bmbm do |x|
x.report("Hash with Strings") do
NUM_TIMES.times do
hash1[strings.sample]
end
end
x.report("Hash with Symbols") do
NUM_TIMES.times do
hash2[symbols.sample]
end
end
end
@kalmanh
Copy link
Author

kalmanh commented May 22, 2014

On my box I get an improvement of about 4 seconds when using symbols...

@yihangho
Copy link

@kalmanh shouldn't the quotes on line 7 be removed?

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