So I was just in racket and was thinking about using keys to interact with the computer and keys are interpreted as strings by racket. I am looking for optimization of my code and was wondering whether strings or symbols are faster to operate on.
If the set of possible keys is well-defined, use symbols. Otherwise, use strings.
The main difference between strings and symbols is that symbols are (by default) interned. With strings, you can have multiple strings that have the same contents, but are different objects (they do not compare as eq?). With symbols, two symbols that have the same contents are guaranteed to be the same object.
The advantage of this is that you can do symbol comparisons using eq?, whereas for strings you have to use string=? or equal?.
However, in order for this magic to happen, behind the scenes, Scheme implementations maintain an intern pool, which is basically like a string-to-symbol hash table. If you call string->symbol and the string is not already in the intern table, it will add the string (and its corresponding symbol) to the table, so if your set of possible keys is not well-defined, you can junk up the intern table pretty quickly.
Edit: When you say "keys", did you mean keyboard characters? That is definitely a well-defined set, so you can use symbols.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With