Justin Collins
2/11/2008 10:13:00 PM
Rick DeNatale wrote:
> On 2/11/08, J. Cooper <nefigah@gmail.com> wrote:
>
>> I ran into something I hadn't realized (common occurrence). Keying a
>> hash with a symbol is not the same as using a string. I guess it makes
>> sense, but I've seen it done both ways, and I had been always using
>> symbols for my keys. But then I ran into an issue on loading an external
>> YAML object into a hash, and didn't realize it was keyed with strings so
>> I got errors the first time around.
>>
>> So two questions:
>> 1) What is the preferred method of keying hashes? Symbols, strings,
>> other?
>>
>
> Symbol keys
> + :a is one less keystroke than "a"
> +? performance of Hash with symbol keys MIGHT be slightly
> faster, but probably insignificant.
> - More symbols get interned which can't get garbage
> collected, even after the hash is.
>
> String keys
>
> + keys can be GCed when removed from hash, or when the hash is GCed.
>
Another thing to look at is symbols are unique, whereas each time you
use a string literal to access the hash, you are creating a new object:
h1 = { :a => 1, :b => 2 }
h2 = { "a" => 1, "b" => 2 }
h2["a"] # Creates a one-time use string "a"
h1[:a] #No new object created, :a already exists
But if you are creating lots and lots of symbols, then that's lots of
unique objects being created which are not going to be garbage collected.
Of course, strings and symbols are not the only choices for hash keys,
any object can be used. What you want may depend on the circumstances.
-Justin