Is string interning really useful?

前端 未结 7 2042
北恋
北恋 2020-12-30 00:26

I was having a conversation about strings and various languages a while back, and the topic of string interning came up. Apparently Java and the .NET framework do this auto

7条回答
  •  梦谈多话
    2020-12-30 00:55

    The points you listed are all valid to a certain extent. But there are important counter-arguments.

    1. Immutability is very important, especially if you're using hash maps, and they are used a lot.
    2. String composition operations are very slow anyway, because you have to constantly reallocate the array containing the characters.
    3. On the other hand, subString() operations are very fast.
    4. String equality is indeed used a lot, and you're not losing anything there. The reason being that strings aren't interned automatically. In fact in Java if the references are different, equals() falls back to a character by character comparison.
    5. Clearly, using strong references for the intern table isn't a good idea. You have to live with the GC overhead.
    6. Java string handling was designed to be space-efficient, especially on constant strings and substring operations.

    On balance I'd say it is worth it in most cases and fits well with the VM-managed heap concept. I could imagine some special scenarios where it could be a real pain though.

提交回复
热议问题