• Python中字符串的intern机制


    intern机制:

      字符串类型作为Python中最常用的数据类型之一,Python解释器为了提高字符串使用的效率和使用性能,做了很多优化,例如:Python解释器中使用了 intern(字符串驻留)的技术来提高字符串效率,什么是intern机制?即值同样的字符串对象仅仅会保存一份,放在一个字符串储蓄池中,是共用的,当然,肯定不能改变,这也决定了字符串必须是不可变对象。

    简单原理:

      实现 Intern 机制的方式非常简单,就是通过维护一个字符串储蓄池,这个池子是一个字典结构,如果字符串已经存在于池子中就不再去创建新的字符串,直接返回之前创建好的字符串对象,如果之前还没有加入到该池子中,则先构造一个字符串对象,并把这个对象加入到池子中去,方便下一次获取。

    但是,解释器内部对intern 机制的使用策略是有考究的,有些场景会自动使用intern ,有些地方需要通过手动方式才能启动,看下面几个常见的小陷阱。

    1.在shell中示例,并非全部的字符串都会采用intern机制。仅仅包括下划线、数字、字母的字符串才会被intern,当然不能超过20个字符。因为如果超过20个字符的话,解释器认为这个字符串不常用,不用放入字符串池中。

    >>> s1="hello"
    >>> s2="hello"
    >>> s1 is s2
    True
    # 如果有空格,默认不启用intern机制
    >>> s1="hell o" >>> s2="hell o" >>> s1 is s2 False
    # 如果一个字符串长度超过20个字符,不启动intern机制
    >>> s1 = "a" * 20 >>> s2 = "a" * 20 >>> s1 is s2 True >>> s1 = "a" * 21 >>> s2 = "a" * 21 >>> s1 is s2 False >>> s1 = "ab" * 10 >>> s2 = "ab" * 10 >>> s1 is s2 True >>> s1 = "ab" * 11 >>> s2 = "ab" * 11 >>> s1 is s2 False

    2.但是在pycharm中,只要是同一个字符串不超过20个字符,都为True,并不用是下划线、数字、字母的字符串。个人理解:IDE支持的不好。

    s1 = "hell o"
    s2 = "hell o"
    print(s1 is s2)  # True
    s1 = "hell!*o"
    s2 = "hell!*o"
    print(s1 is s2)  # True
    s1 = "a" * 20
    s2 = "a" * 20
    print(s1 is s2)  # True
    s1 = "a" * 21
    s2 = "a" * 21
    print(s1 is s2)  # False
    s1 = "ab" * 10
    s2 = "ab" * 10
    print(s1 is s2)  # True
    s1 = "ab" * 11
    s2 = "ab" * 11
    print(s1 is s2)  # False

    3.字符串拼接时,涉及编译运行问题

    >>> s1 = "hell"
    >>> s2 = "hello"
    >>> s1 + "o" is s2
    False
    >>> "hell" + "o" is s2
    True
    >>>
    # 说明shell和IDE在这方面没有差异
    s1 = "hell"
    s2 = "hello"
    print(s1 + "o" is s2)  # False
    print("hell" + "o" is s2)  # True
    #因为"hell" + "o"在编译时已经变成了"hello",而s1+"o"因为s1是一个变量,他们会在运行时进行拼接,所以没有被intern
  • 相关阅读:
    .NET中非对称加密RSA算法的密钥保存
    WGS84经纬度坐标到北京54高斯投影坐标的转换[转]
    [APPS] HTC Footprints & HTC Locations for MikG 2.x Read more:
    firefox+ssh无法看youtube视频的解决方案
    【转】sdemon命令实践
    How to share a custom ArcMap command (DLL)
    【转】sdemon命令实践
    红旗桌面版本最新运用法子和结果解答100例8
    红旗Linux桌面4.1文本安装过程图解(二)
    Ubuntu把在效能器范畴起更重要的脚色
  • 原文地址:https://www.cnblogs.com/greatfish/p/6045088.html
Copyright © 2020-2023  润新知