Python:是“旧的"为变量分配新内容时是否释放了内存? [英] Python: is the "old" memory free'd when a variable is assigned new content?

查看:156
本文介绍了Python:是“旧的"为变量分配新内容时是否释放了内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果为变量分配了任何新内容,分配给旧内容"的内存是否将被适当"释放?例如,在下面的脚本中,在为"a"分配了一些新内容之后,将释放作为零数组的变量"a"的内存

If a variable is assigned any new content, will the memory allocated for the "old content" be "properly" free'd? For example, in the following script, will the memory for variable "a" as an array of zeros be free'd after "a" is assigned some new stuff

import numpy
a = numpy.zeros(1000)
a = a+1

我想想,Python足够聪明,可以使用所谓的垃圾收集"来干净地完成所有工作,而我从来没有真正读过它.任何确认吗?我会很感激的.

I would imaging Python is smart enough to do everything cleanly, using the so-called 'garbage collection', which I never really be able to read through. Any confirmation? I'd appreciate it.

推荐答案

最终,旧内存将被释放,尽管您无法预测何时会发生这种情况.它取决于Python的实现和许多其他因素.

Eventually, the old memory will be freed, though you cannot predict when this will happen. It is dependent on the Python implementation and many other factors.

也就是说,对于您给出的示例和CPython实现,应该在分配过程中对旧数组进行垃圾回收.

That said, for the example you gave and the CPython implementation, the old array should be garbage collected during the assignment.

(请注意,NumPy数组是讨论垃圾收集器行为的特别复杂的示例.)

(Note that NumPy arrays are a particularly complex example for discussing garbage-collector behaviour.)

这篇关于Python:是“旧的"为变量分配新内容时是否释放了内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆