When are objects garbage collected in python?(什么时候在python中收集对象垃圾?)
问题描述
什么时候在 python 中收集对象垃圾?什么时候释放内存,收集是否影响性能?可以选择退出或调整 gc 算法吗?如果可以,如何选择?
When are objects garbage collected in python? When is the memory released and does the collection impact performance? Can one opt out or tune the gc algorithm and if so how?
推荐答案
这里摘自 语言参考
对象永远不会被显式销毁;但是,当它们变得无法访问时,它们可能会被垃圾收集.允许实现推迟垃圾收集或完全忽略它 - 只要没有收集仍然可访问的对象,垃圾收集的实现方式就是实现质量的问题.
Objects are never explicitly destroyed; however, when they become unreachable they may be garbage-collected. An implementation is allowed to postpone garbage collection or omit it altogether — it is a matter of implementation quality how garbage collection is implemented, as long as no objects are collected that are still reachable.
CPython 实现细节:CPython 目前使用引用计数方案,对循环链接的垃圾进行(可选)延迟检测,该方案在大多数对象变得无法访问时立即收集它们,但不能保证收集包含循环引用的垃圾.有关控制循环垃圾收集的信息,请参阅 gc 模块的文档.其他实现的行为不同,CPython 可能会改变.当对象变得无法访问时,不要依赖于立即完成对象(例如:始终关闭文件).
CPython implementation detail: CPython currently uses a reference-counting scheme with (optional) delayed detection of cyclically linked garbage, which collects most objects as soon as they become unreachable, but is not guaranteed to collect garbage containing circular references. See the documentation of the gc module for information on controlling the collection of cyclic garbage. Other implementations act differently and CPython may change. Do not depend on immediate finalization of objects when they become unreachable (ex: always close files).
关于推迟垃圾回收 .... gc
模块允许您与垃圾收集器进行交互,如果您愿意,可以禁用它并更改收集频率等.但我自己没有使用它.此外,包含具有 __del__
方法的任何对象的循环 不收集.
About postponing garbage collection .... the gc
module allows you to interact with the garbage collector, and disable it if you want to and change collection frequency etc. But I have not used it myself. Also, cycles that contain any objects with __del__
methods are not collected.
这篇关于什么时候在python中收集对象垃圾?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:什么时候在python中收集对象垃圾?
基础教程推荐
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 筛选NumPy数组 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01