是否需要删除以释放内存

Dav*_*542 2 python python-3.x

我有以下代码,在其中我重新分配了几个GB的列表:

    res = self.dict_cursor.fetchall()
    res_with_offers = []

    # we add in HDBUY, SDBUY for now -- HARDCODED
    for item in res:
        for avail_code in ['HDBUY', 'SDBUY']:
            _item = deepcopy(item)
            _item['avail_code'] = avail_code
            res_with_offers.append(_item)

    del res; # <== is this line needed?
    res = res_with_offers
Run Code Online (Sandbox Code Playgroud)

我的理解是del res;,作为下一行中的变量重新分配,它将删除res内存中的初始项。它是否正确?为什么或者为什么不?

Tim*_*ers 5

标识符可以绑定到Python中的对象,也可以不绑定任何东西。就这样。

如果identifier绑定到对象,则del identifier删除绑定,identifier不绑定任何对象。而而已。它对是否释放内存没有直接影响。

删除与对象的最后一个绑定后,该对象即可进行垃圾回收。在那之前

在显示的代码中,实际上无法确定最初绑定到的对象何时有res资格进行垃圾回收。就我们所知,例如

res = self.dict_cursor.fetchall()
Run Code Online (Sandbox Code Playgroud)

fetchall()从内部持续高速缓存返回的对象。然后

del res
Run Code Online (Sandbox Code Playgroud)

将通过删除与对象的绑定res,但对与该对象的任何其他可能的绑定都没有影响。在所有绑定消失之前,无法回收该对象。

无论如何,del resin:

del res
res = anything
Run Code Online (Sandbox Code Playgroud)

没有真正的目的。 res最终anything不管是否del res存在,都被绑定到,因此,无论是否存在,res都将删除的原始绑定del res