gpt4 book ai didi

python内存删除列表[:] vs list = []

转载 作者:太空宇宙 更新时间:2023-11-03 12:52:17 25 4
gpt4 key购买 nike

在 python 中,我注意到如果你这样做

mylist = []

for i in range(0,100000000):
mylist.append('something here to take memory')

mylist = []

好像是第二次调用

mylist = []

会删除引用并且它会被收集但是,当我看着他们的内存时它不会。

当我使用

del mylist[:]

它几乎删除了除几兆之外的所有内容(只看过程)

当我使用

del mylist[:]
gc.collect()

我似乎会返回到创建列表之前相同数量的内存

所以....为什么

mylist = []

不工作???据我所知,没有其他东西引用它

最佳答案

你如何衡量它?

我做了一个小测试,但不能证实你的结果。这是来源:

import meminfo, gc, commands

page_size = int(commands.getoutput("getconf PAGESIZE"))

def stat(message):
s = meminfo.proc_stat()
print "My memory usage %s: RSS: %dkb, VSIZE: %dkb" % (
message, s['rss']*page_size/1024, s['vsize']/1024)
mylist = []

stat("before allocating a big list")
for i in range(0,3000000):
mylist.append('something here to take memory')

stat("after allocating big list")
### uncomment one of these:
mylist = []
# del mylist[:]
stat("after dropping a big list")
gc.collect()
stat("after gc.collect()")
gc.collect()
stat("after second gc.collect()")
gc.collect()
stat("after third gc.collect()")

使用的内存信息模块在这里:http://gist.github.com/276090

这些是 mylist=[] 的结果:

My memory usage before allocating a big list: RSS: 3396kb, VSIZE: 7324kb
My memory usage after allocating big list: RSS: 50700kb, VSIZE: 55084kb
My memory usage after dropping a big list: RSS: 38980kb, VSIZE: 42824kb
My memory usage after gc.collect(): RSS: 38980kb, VSIZE: 42824kb
My memory usage after second gc.collect(): RSS: 38980kb, VSIZE: 42824kb
My memory usage after third gc.collect(): RSS: 38980kb, VSIZE: 42824kb

这是 del mylist[:] 的结果:

My memory usage before allocating a big list: RSS: 3392kb, VSIZE: 7324kb
My memory usage after allocating big list: RSS: 50696kb, VSIZE: 55084kb
My memory usage after dropping a big list: RSS: 38976kb, VSIZE: 42824kb
My memory usage after gc.collect(): RSS: 38976kb, VSIZE: 42824kb
My memory usage after second gc.collect(): RSS: 38976kb, VSIZE: 42824kb
My memory usage after third gc.collect(): RSS: 38976kb, VSIZE: 42824kb

Python 可以为其自己的堆分配内存,但不一定会在垃圾回收后立即释放它。

关于python内存删除列表[:] vs list = [],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2055107/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com