So while a ruby String
is globally unique, a ruby Symbol
is not, because it's stored by id somewhere in the background:
http://thoughtsincomputation.com/posts/ruby-symbols-what-are-they
...which means using symbols use less memory, given that you have a specified set of values the symbol can be (you don't want to turn every string of user-entered text into a symbol for example).
My question is, while there is definitely a performance benefit of using symbols, is it worth it in the end? I'm asking because, for example, I write most of my hashes using symbols:
my_hash = {:_id => "123", :key => "value"}
But in the ruby-mongo-driver, all the keys are returned as strings:
mongo_hash = {"_id" => "123", "key" => "value"}
So if I were to use both my hash and the mongo hash the same way, I'd have to do:
mongo_hash = Model.collection.find_one(:key => "value")
#=> {"_id" => "123", "key" => "value"}
mongo_hash.symbolize_keys!
#=> {:_id => "123", :key => "value"}
But that just adds another layer to the application:
- Create a bunch of strings for the keys in memory.
- Now create a symbol for each string (already in memory after the first time this is done).
- Now destroy the strings we just created.
It seems like something's wrong there... either everything should be symbols or strings, there shouldn't be conversion back and forth, at least in this case.
What do you think about this? Is this okay? Is this even a problem, or is the ruby garbage collector and all that (haven't gone there yet) okay with this?