views:

274

answers:

4

Every text I've read about Ruby symbols talks about the efficiency of symbols over strings. But, this isn't the 1970s. My computer can handle a little bit of extra garbage collection. Am I wrong? I have the latest and greatest Pentium dual core processor and 4 gigs of RAM. I think that should be enough to handle some Strings.

+1  A: 

It's nice that symbols are guaranteed unique--that can have some nice effects that you wouldn't get from String (such as their addresses are always exactly equal I believe).

Plus they have a different meaning and you would want to use them in different areas, but ruby isn't too strict about that kind of stuff anyway, so I can understand your question.

Bill K
+11  A: 

It's true, you don't need tokens so very badly for memory reasons. Your computer could undoubtedly handle all kinds of gnarly string handling.

But, in addition to being faster, tokens have the added advantage (especially with context coloring) of screaming out visually: LOOK AT ME, I AM A KEY OF A KEY-VALUE PAIR. That's a good enough reason to use them for me.

There's other reasons too... and the performance gain on lots of them might be more than you realize, especially doing something like comparison.

When comparing two ruby symbols, the interpreter is just comparing two object addresses. When comparing two strings, the interpreter has to compare every character one at a time. That kind of computation can add up if you're doing a lot of this.

Symbols have their own performance problems though... they are never garbage collected.

It's worth reading this article: http://www.randomhacks.net/articles/2007/01/20/13-ways-of-looking-at-a-ruby-symbol

danieltalsky
Interesting. I didn't think about the fact that symbols are not garbage collected. Cool article. Thanks for the link. That's like, "Everything you ever wanted to know about Symbols" :) Peace, dude.
The context coloring thing is a good point too.
+14  A: 

Your computer may well be able to handle "a little bit of extra garbage collection", but what about when that "little bit" takes place in an inner loop that runs millions of times? What about when it's running on an embedded system with limited memory?

There are a lot of places you can get away with using strings willy-nilly, but in some you can't. It all depends on the context.

Colen
Yeah, that's true - a long running loop could definitely eat up resources. Didn't think about creating strings inside a loop but, sure, I guess you might do that. Thanks for the tip.
+2  A: 

One less character to type. That's all the justification I need to use them over strings for hash keys, etc.

Luke
+1; When I first read this, I said to myself, "Wow, what a superficial reason!". But the more I thought about it, the more I realized how big this was a motivation for my own usage of symbols. Thanks for helping me realize something about myself.
Justin L.