Why have a Symbol class?

R

rolo

Hi

As far as I understand Symbols are interned Strings. Why have a different
Symbol class? Any advantages?


Regards,
Rohit
 
H

Hal Fulton

rolo said:
Hi

As far as I understand Symbols are interned Strings. Why have a different
Symbol class? Any advantages?

I would say it's a matter of efficiency in time and space, and maybe
a small psychological gain.

Note that:
1. Symbols are immutable
2. Only one instance of a given Symbol ever exists
3. I think they're stored specially, but I'm not sure of
the details

I had a fourth point, but I lost it. :)

Hal
 
P

Paul Brannan

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,146
Messages
2,570,832
Members
47,374
Latest member
anuragag27

Latest Threads

Top