|
|
|
|
|
by bjoli
1534 days ago
|
|
In scheme you usually use symbols instead of strings because the whole equality story is simpler and much faster. I once changed a tight loop in some code from dispatching on strings to dispatching on symbols and got a 15% speedup. Why? String equality is expensive. A symbol is basically a readable fixnum, where two similar symbols are always the same objects (errr... Don't quote me on that because it isn't strictly true). Most places where you can use symbols instead of strings you lose nothing and gain speed. I am not sure how it is in ruby though. |
|
OTOH, symbols return true for both: they are the exact same object.
It's not just about speed though: symbols are somewhat limited in what they can be made of. They follow the same limitations as methods and variables. So often symbols are used when dynamically calling methods or assigning variables.
"Foo".public_send(:strip!) ¹. Which is slightly different from "Foo".public_send('strip!'). Not in outcome, but in calling. Because this is invalid syntax: "Foo".public_send(:one-two three) whereas this isn't: "Foo".public_send('one-two three'). Technically, I guess Ruby can have a method that is named "one-two three" but that would be really nasty to call. Symbols protect a lot against this.
And therefore are used in this context a lot.
¹ The exclamation mark can be a part of a method and symbol in ruby. As can the question-mark and some other sugar-ish stuff like [].