Skip to main content
 首页 » 编程设计

python之为什么即使禁用了 gc,python 仍在收集

2024年11月01日9me-sa

这段代码

import gc 
gc.disable() 
print gc.isenabled() 
print len(gc.get_objects()) 
class Foo(): pass 
print len(gc.get_objects()) 
 
a=[] 
print len(gc.get_objects()) 
for i in xrange(10000): 
    a.append(Foo()) 
 
print len(gc.get_objects()) 
a=[] # Should not collect 
print len(gc.get_objects()) 
gc.collect() 
print len(gc.get_objects()) 

产生这个输出

False 
3754 
3755 
3756 
13756 
3756 
3374 

我希望倒数第二个数字是 13756,因为 gc 被禁用并且当原始 a 列表超出范围时,它不应该丢弃这些对象。显然 python 正在收集这些对象。为什么?

python 是 2.7.2

请您参考如下方法:

因为垃圾回收只处理循环引用。引用自 gc module documention :

Since the collector supplements the reference counting already used in Python, you can disable the collector if you are sure your program does not create reference cycles.

CPython 使用引用计数来清理大多数 对象。当您用一个空列表替换引用的列表 a 时,旧列表的引用计数降为 0,因此此时被删除。删除列表会导致 Foo() 实例的引用计数也降为 0,等等。

如果您改为创建循环引用,和禁用垃圾回收,您会看到数字保持不变:

class Foo(object): 
    def __init__(self): 
         self.bar = Bar(self) 
 
class Bar(object): 
    def __init__(self, foo): 
        self.foo = foo