Pages

Showing posts with label Ruby Strings. Show all posts
Showing posts with label Ruby Strings. Show all posts

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