代码之家  ›  专栏  ›  技术社区  ›  Amir reza Riahi

为什么None对象的引用计数是固定的?

  •  0
  • Amir reza Riahi  · 技术社区  · 10 月前

    我正在尝试对象的引用计数,我注意到 None 当我将标识符绑定到时,对象不会改变 没有 我在python版本中观察到了这种行为 3.13 .

    Python 3.13.0 (main, Oct  7 2024, 05:02:14) [Clang 16.0.0 (clang-1600.0.26.4)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import sys
    >>> sys.getrefcount(None)
    4294967295
    >>> list_of_nones = [None for _ in range(100)]
    >>> sys.getrefcount(None)
    4294967295
    >>> del list_of_nones
    >>> sys.getrefcount(None)
    4294967295
    

    这种行为与python的行为形成对比 3.10 :

    Python 3.10.15 (main, Sep  7 2024, 00:20:06) [Clang 15.0.0 (clang-1500.3.9.4)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import sys
    >>>
    >>> sys.getrefcount(None)
    4892
    >>> list_of_nones = [None for _ in range(100)]
    >>> sys.getrefcount(None)
    4990
    >>>
    >>> del list_of_nones
    >>>
    >>> sys.getrefcount(None)
    4890
    

    在the 3.10 版本,引用计数 没有 ,根据绑定标识符和删除标识符进行增减。但在3.13中,引用计数始终是固定的。 有人能解释一下这种行为吗?

    1 回复  |  直到 10 月前
        1
  •  1
  •   user2357112    10 月前

    这是由于 PEP 683 为了避免需要写入某些“不朽”对象的内存,例如 None ,这些对象现在有一个固定的引用数,无论存在多少对该对象的实际引用,该引用数都不会改变。

    这有助于提高多线程和多进程性能,避免缓存失效和写时复制等问题。

    推荐文章