4 ms·
Useful, yes. > as of Ruby 2.2, there are zero-performance gains using symbols over strings This is verifiably false. Run this on a newer Ruby and you will see
by rokob 8y ago
Useful, yes.
> as of Ruby 2.2, there are zero-performance gains using symbols over strings
This is verifiably false. Run this on a newer Ruby and you will see symbols are faster:
```
require 'benchmark'
hashes = []
1_000_000.times { hashes << { some_key_name: 1, 'some_key_name' => 2 }}
Benchmark.bmbm do |x|
x.report { hashes.map{|h| h[:some_key_name]} }
x.report { hashes.map{|h| h['some_key_name']} }
end
```
But that isn't the reason symbols are useful. They signify intent as a constrained set of alternatives. Strings can take on any value, symbols should be limited to a set of things you know. Strings can be modified in-place, symbols are immutable.
`opts = { :adapter => :mysql }` is perfectly valid for scenarios where you are using symbol values. But the shorthand syntax for symbol keys was added later, and I agree is a bit ugly.
If you are generating symbols from input or from strings then they lose some value.
It is easy to explain the existence of symbols in Ruby especially if you are giving proper merit to the Smalltalk lineage. Erlang also has symbols for a lot of the same reasons and most would agree they are very useful there.