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

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