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

查看:25
本文介绍了什么时候在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天全站免登陆