什么时候在python中垃圾收集对象? [英] When are objects garbage collected in python?

查看:26
本文介绍了什么时候在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中垃圾收集对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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