【问题标题】:Does deleting/reassigning a python list allow for garbage collection?删除/重新分配 python 列表是否允许垃圾收集?
【发布时间】:2015-02-04 14:40:55
【问题描述】:

我知道当 Python 知道不再有任何对事物的引用时,它会清除事物的内存。在我的代码中,我正在模拟一段时间内的人口。

个人出生并最终死亡。当他们死去时,我希望他们从记忆中消失。但与此同时,我已将它们放入各种列表中,然后我将其删除。垃圾收集是否知道它们已经消失,所以它会从内存中清除它们吗?我对代码中内存的跟踪(通过 guppy)表明某处的内存量正在缓慢增加。

这是一个示例代码,它会在每个时间步创建 4 个人,将他们放入一个列表中,然后转到下一个时间步并用一组新的 4 个替换这 4 个。我的问题是他们何时被替换垃圾收集器会意识到它们已经消失了。

class Person:
    def __init__(self,year,id):
        self.id = (year,id)


for year in xrange(100):
    tmplist = []
    for counter in range(4):
        tmplist.append(Person(year,counter))

    mainlist = tmplist
    #do operations to mainlist, but leave it there until replacing it next time through.

(如果您有后续问题,我们深表歉意 - 我在墨尔本时间,所以我要去睡觉了)

【问题讨论】:

标签: python python-2.7 garbage-collection


【解决方案1】:

您可以使用sys.getrefcount 对此进行试验(请注意,结果 " 通常比您预期的要高一个,因为它包含(临时)引用作为 getrefcount()" 的参数 ):

>>> import sys
>>> class Person(object):
    pass

>>> list1 = [Person() for _ in range(5)]
>>> sys.getrefcount(list1[0])
2  # list1 and getrefcount
>>> list2 = list1[:]
>>> sys.getrefcount(list2[0])
3  # list1, list2 and getrefcount
>>> del list1  # or just reassign e.g. list1 = None
>>> sys.getrefcount(list2[0])
2  # list2 and getrefcount

删除列表(如果它超出范围或明确deleted 如上所述)会减少其中对象的引用计数,因此如果没有其他现存引用(即该列表是它们的最后一个位置)被引用)它们的引用计数将降至零,最终将被垃圾回收。

【讨论】:

  • list1 = list2[:]list1 = list2 之间是否存在相应的差异?
  • 是的! list1 = list2[:] 复制 list2 中的引用;您可以更改 list1 而不会影响 list2。 list1 = list2 将 list1 指向同一个列表对象;如果您通过 list1 修改列表,则 list2 会看到相同的更改。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-11-28
  • 1970-01-01
  • 1970-01-01
  • 2012-12-20
  • 2012-11-17
  • 2013-01-26
  • 2011-07-24
相关资源
最近更新 更多