From: Rick DeNatale Date: 2009-11-03T23:06:09+09:00 Subject: Re: Merging hashes using both symbols and strings as keys On Tue, Nov 3, 2009 at 8:40 AM, Josh Cheek wrote: > On Tue, Nov 3, 2009 at 7:27 AM, Paul Smith wrote: > >> >> A big difference here is that a pastie is only available through >> pastie.org, a gist is a git repository that can be cloned. >> > > > Here is the code in a gist http://gist.github.com/225048 It might be of interest to note that this code basically take the opposite tack from the HashWithIndifferentAccess which is part of ActiveSupport and therefore Rails. HashWithIndifferentAccess (which I'll abbreviate to HWIA) converts symbol keys to strings in the access methods ([], []= etc.) Contrary to some people's thinking (including mine when I first encountered it) the actual keys in the hash are strings, not symbols. The trade-offs between the two approaches include: 1) Symbols once created can't be garbage collected. Since Rails uses HWIA for things like the params hash, and the keys come from parts of arbitrary client provided URIs this could be an opening for a DOS attack which creates tons of useless extra parameters which result in non-GCable symbols. Since HWIA uses strings, for the keys, keys coming from query parameters and the like never get turned into symbols. The only symbols will be those coming from the application itself. 2) Using strings for the keys is slightly slower on access because computing the hash value of a string is O(length of the string) while the hash value of a symbol is computed once and is O(1) subsequently. On the other hand this only becomes significant if the same key is used to access the hash multiple times, since interning a string as a symbol requires computing the hash of the string anyway. In practice, and particularly for the typical usage in Rails apps, I doubt that there's any real effect on performance from storing strings rather than symbols for the keys. The main advantage of HWIA is that it allows you to save a keystroke params[:id] vs params['id'] and some think the former looks a little bit nicer. Although this is no doubt a potential source of controversy. I for one have a slight preference for the :id form, but that might be the result of Stockholm syndrome having worked on so many Rails apps. -- 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