Strings vs Symbols

When you make a hash, for the keys do you use a symbol or a string? I always use a string, because I was never 100% sure what the difference was and I felt more comfortable with a string.

BUT, apparently a symbol can be better because it will save time and memory. So, here I am writing the differences down, so I remember it. I am using this highly rated answer from Stackoverflow.

Symbols in Ruby are basically immutable strings, which means that they never change, and whenever you reference it it will still have the same object id.

Strings on the other hand are mutable. They can change. Therefore, Ruby stores each string you mention in your code as a separate entity, just in case it changes. e.g. if you use the string “rosebud” multiple times in your code, every time you mention it, it will be stored as a separate entity (same string value, different object id).

So, in irb it might look like this:

:steve.object_id=> 1234
"steve".object_id=>1235
:steve.object_id=> 1234
"steve".object_id=>1236
"steve".object_id=>1237
:steve.object_id=> 1234

So, no matter how many times I call object_id on :steve it returns the same number.

BUT each time I call it on “steve” it returns a new number.

If you use a Symbol as your key in a hash, your program just has to compare the object_id of that Symbol with the object_id’s of the keys in the hash. I

f you choose to use a String, it first has to evaluate the string, then compute a hash function on it, then compare it to the hashed values of all the keys in the hash.

Apparently a downside of using symbols is that they take a place in Ruby’s interpreter’s symbol table, and won’t release it. I’m not exactly sure yet what this means for anyone.

 

Leave a reply