Pages

Wednesday, May 1, 2013

Difference between a Symbol and String

Symbols and string are used interchangeably by various developers and their usage within gems can be confusing at times. You can think of Symbols as faster & immutable strings.
Once a string is used up it is marked for cleaning by the garbage collector but it is not cleaned up immediately and it cannot be reused.
Symbols live for the duration of the session. You might say that this leads to increased memory usage however by keeping the symbol alive a bit longer it can be reused again. 
Here’s a terminal irb session that will provide more insight. 


puts :"I am a symbol".object_id
457908

puts :"I am a symbol".object_id
457908

puts :"I am a symbol".object_id
457908

puts "I am a string".object_id
70343000106700

puts "I am a string".object_id
70343000094220



Notice that the object_id stays the same when symbols are created. This happens because the ruby interpreter uses the same heap memory location each time. The symbol was never completely released.
However, in the case of strings the memory is marked for cleanup each time and a new memory is allocated. 
Another big difference is that strings can be modified. They are mutable.
So, this would work:
puts "I am a string" << " for you"
I am a string for you
However, symbols are immutable. 
So, this would throw an error:
puts :"I am a symbol" << :" for you"
NoMethodError: undefined method `<<' for :"I am a symbol":Symbol

from (irb):16
from /Users/anilo/.rvm/rubies/ruby-1.9.3-p0/bin/irb:16:in `<main>'
1.9.3p0 :017 > puts :"I am a symbol" << " for you"
NoMethodError: undefined method `<<' for :"I am a symbol":Symbol

1 comment: