Under which circumstances do equal strings share the same reference?

前端 未结 3 1116
南笙
南笙 2020-12-19 03:04

I have searched the web and stack overflow questions but been unable to find an answer to this question. The observation that I\'ve made is that in Python 2.7.3, if you assi

3条回答
  •  情书的邮戳
    2020-12-19 03:38

    In CPython, as an implementation detail the empty string is shared, as are single-character strings whose codepoint is in the Latin-1 range. You should not depend on this, as it is possible to bypass this feature.

    You can request a string to be interned using sys.intern; this will happen automatically in some cases:

    Normally, the names used in Python programs are automatically interned, and the dictionaries used to hold module, class or instance attributes have interned keys.

    sys.intern is exposed so that you can use it (after profiling!) for performance:

    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.

    Note that intern is a builtin in Python 2.

提交回复
热议问题