Why string interning when strings are immutable?

There is a lot of overhead to interning a string, which wouldn’t be acceptable for generic runtime string manipulations.

It makes sense for symbols that are used in metaprogramming, because usually you only have a relatively small number of symbols, and runtime overhead in generating expressions is less of a concern (since expression generation usually occurs only once, at compile time). Symbols are also used for tagging types and other “symbolic label” purposes unrelated to metaprogramming, for which interning is important for performance — e.g. if you have a MyType{:foo}, or are passing :foo as an enum-like symbolic constant to a function.

That being said, if you have a specialized application where string interning makes sense, but you still want to support generic string operations like searching (which don’t work for Symbol), you can use InternedStrings.jl — see also the discussion in [ANN] InternedStrings.jl: Allocate strings once and reuse them

4 Likes