Hi
As far as I understand Symbols are interned Strings. Why have a different
Symbol class? Any advantages?
It is for efficiency. A Symbol is just an entry in the symbol table;
it's hash value is the same as its object id:
irb(main):001:0> :foo.id
=> 3979534
irb(main):002:0> :foo.hash
=> 3979534
Compare this to a String, where the hash value is computed based on the
String's value:
irb(main):003:0> "foo".id
=> 537781650
irb(main):004:0> "foo".hash
=> 876516207
The result is that hash operations with Symbols are much faster:
irb(main):005:0> require 'benchmark'
=> true
irb(main):006:0> puts Benchmark.measure {
irb(main):007:1* h = {}; 1000000.times { h[:foo] = 1 }
irb(main):008:1> }
0.960000 0.010000 0.970000 ( 0.975577)
=> nil
irb(main):009:0> puts Benchmark.measure {
irb(main):010:1* h = {}; 1000000.times { h["foo"] = 1 }
irb(main):011:1> }
2.410000 0.000000 2.410000 ( 2.427366)
=> nil
Paul