Is string interning really useful?

前端 未结 7 2025
北恋
北恋 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:46

    Here's the python documentation's take on it:

    sys.intern(string)

    Enter string in the table of “interned” strings and return the interned string – which is string itself or a copy. Interning strings is useful to gain a little performance on dictionary lookup – if the keys in a dictionary are interned, and the lookup key is interned, the key comparisons (after hashing) can be done by a pointer compare instead of a string compare. Normally, the names used in Python programs are automatically interned, and the dictionaries used to hold module, class or instance attributes have interned keys.

    Interned strings are not immortal; you must keep a reference to the return value of intern() around to benefit from it.

提交回复
热议问题