Strings vs Symbols ruby hash
irb(main):029:0> Benchmark.bm do |x| | |
irb(main):030:1* x.report("Strings: ") { 10000000.times {"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".hash} } | |
irb(main):031:1> x.report("Symbols: ") { 10000000.times {:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.hash} } | |
irb(main):032:1> end | |
user system total real | |
Strings: 1.290000 0.000000 1.290000 ( 1.282911) | |
Symbols: 0.450000 0.000000 0.450000 ( 0.458915) |
This comment has been minimized.
This comment has been minimized.
eregon
commented
Oct 5, 2017
•
The benchmarks above account for allocating the Strings (except the But if we use different String lengths we see String#hash is O(n) but Symbol#hash O(1) and so we can get arbitrary speedups. require 'benchmark'
len = Integer(ARGV[0])
n = 1_000_000
base = "a" * len
STRINGS = Array.new(n) { |i| base + n.to_s }
SYMBOLS = STRINGS.map(&:to_sym)
Benchmark.bm do |x|
x.report("Symbol#hash") do
SYMBOLS.each { |s| s.hash }
end
x.report("String#hash") do
STRINGS.each { |s| s.hash }
end
end
|
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This comment has been minimized.
paneq commentedOct 2, 2017
•
edited