Why symbol instead of string in Ror?

When you place a colon in front of a simple word, you get a symbol. Symbols are cheaper than strings (in terms of computer memory.) If you use a word over and over in your program, use a symbol. Rather than having thousands of copies of that word in memory, the computer will store the symbol only once.

Symbols are immutable. Mutable objects can be changed after assignment while immutable objects can only be overwritten.

Comparing identical strings is much slower since the string values need to be compared instead of just the object ids.

as you can see:

2.1.1 :009 > :abc.object_id
=> 544168
2.1.1 :010 > :abc.object_id
=> 544168

both are same objects.

……..

2.1.1 :011 > "abc".object_id
=> 6023220
2.1.1 :012 > "abc".object_id
=> 5905340

both are different objects.

As Symbols stay in memory throughout the programs operation, we can quickly snag them from memory instead of instantiating a new copy every time. In fact, Symbols are not only stored in memory, they are also keep track of via an optimized Symbols dictionary. You can see it by running the next example.

puts Symbol.all_symbols.inspect
# => A long list of Symbols...

This being the case, what can’t Symbols do? Well, they can’t change.

2.1.1 :014 > puts "hello" << " world"
hello world
=> nil
2.1.1 :015 > puts :hello << :" world"
NoMethodError: undefined method `<<' for :hello:Symbol
Advertisements

One thought on “Why symbol instead of string in Ror?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s