-
-
Save hubertlepicki/dc7b69b457d9187033d0e0d7c79b19fd to your computer and use it in GitHub Desktop.
Strings vs Symbols ruby hash
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The benchmarks above account for allocating the Strings (except the
var
variants in the comment above).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.
Of course, this is no magic, the time we gain on
Symbol#hash
is the time we pay when creating those Symbols and interning them (i.e. those (14-4) seconds before the benchmark starts in the length=10 000 run).