From: Rick DeNatale Date: 2009-04-02T16:48:53+09:00 Subject: Re: Symbols garbage collector in Ruby1.9, fixed? --001636163c5f4de98104668dabc0 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit On Thu, Apr 2, 2009 at 12:17 AM, Rob Biedenharn wrote: > > If you really need to use symbols, perhaps add methods to a subclass of > Hash like the HashWithIndifferentAccess from Rails which mostly eliminates > the need to care whether you actually stored against a Symbol or a String > key. > > There's also nothing stopping you from having both kinds of keys at once: > headers = { :from => "alice@qweeq", :to => "bob@qweeq", 'snack' => > "raisins" } > > but then you might have to "worry" about having both :to and 'to' as keys. > > Symbols are only faster because they are immutable and don't get garbage > collected. But I'd go with Tony and just use String all the time. > Actually, I'm pretty sure that Symbols are faster as hash keys because Hash#== is O(1) while String#== is O(n) where n is the length of the string. That said, the HashWithIndifferentAccess class in activesupport allows either strings or symbols to be used interchangeably as the key argument in methods like [] and []=, but it always USES the string form as the key. I was quite surprised when I discovered this, since I'd assumed that the reason for using symbols was for the speed advantage, but it was finally pointed out to me the problem of "memory leaks" when arbitrary keys get interned as symbols. But I do in general prefer the look in source code of :id => 3 rather than 'id' = > 3 And when the symbols come in the source like this there's less chance of arbitrary growth of interned symbols. -- Rick DeNatale Blog: http://talklikeaduck.denhaven2.com/ Twitter: http://twitter.com/RickDeNatale WWR: http://www.workingwithrails.com/person/9021-rick-denatale LinkedIn: http://www.linkedin.com/in/rickdenatale --001636163c5f4de98104668dabc0--