Panasonic Youth

Comparing Ruby Symbols to Java String interning

If I’m reading the Kev’s article on Ruby symbols correctly, they are kinda the same as Java interned Strings…except with some more power. A Symbol also is its own type, which would also be somewhat different from Java Strings. It kinda helps explain all the weird keys (to my eyes) used in Rails, so you aren’t recreating the “link” key 500 times in memory. This post in Ruby-Talk (via RubyNews) also provides a nice explanation, which I will quote for your too-lazy-to-click convience:

Symbols are immutable strings. Every occurence of the same symbol correspondes to the same single object, while every occurence of the same string is a different object (with the same value). Thus symbols are a bit faster and cheaper to use in things like case statements, hash keys etc.

It’s also usually a bit nicer to read in the code, as it signifies that what you’re looking it at is a unique identifier, rather than something that can have a dynamic content.</em> - (thanks Assaph Mehr)