python 垃圾回收价格表_python垃圾回收

Python的垃圾回收机制是以:引用计数器为主,标记清除和分代回收为辅。

1. 引用计数器

每个对象内部都维护了一个值,该值记录这此对象被引用的次数,如果次数为0,则Python垃圾回收机制会自动清除此对象。下图是Python源码中引用计数器存储的代码。

784ab570aad47116684e487c54ec4a7a.png

引用计数器的获取及代码示例:

2. 循环引用

通过引用计数器的方式基本上可以完成Python的垃圾回收,但它还是具有明显的缺陷,即:“循环引用”。

注意:gc.collect() 可以主动触发垃圾回收;

循环引用的问题会引发内存中的对象一直无法释放,从而内存逐渐增大,最终导致内存泄露。

为了解决循环引用的问题,Python又在引用计数器的基础上引入了标记清除和分代回收的机制。

so,不必再担心循环引用的问题了。

Reference cycles involving lists, tuples, instances, classes, dictionaries, and functions are found.

3. 标记清除&分代回收

Python为了解决循环引用,针对 lists, tuples, instances, classes, dictionaries, and functions 类型,每创建一个对象都会将对象放到一个双向链表中,每个对象中都有 _ob_next 和 _ob_prev 指针,用于挂靠到链表中。

随着对象的创建,该双向链表上的对象会越来越多。

当对象个数超过 700个 时,Python解释器就会进行垃圾回收。

当代码中主动执行 gc.collect() 命令时,Python解释器就会进行垃圾回收。

Python解释器在垃圾回收时,会遍历链表中的每个对象,如果存在循环引用,就将存在循环引用的对象的引用计数器 -1,同时Python解释器也会将计数器等于0(可回收)和不等于0(不可回收)的一分为二,把计数器等于0的所有对象进行回收,把计数器不为0的对象放到另外一个双向链表表(即:分代回收的下一代)。

关于分代回收(generations):

The GC classifies objects into three generations depending on how many collection sweeps they have survived. New objects are placed in the youngest generation (generation 0). If an object survives a collection it is moved into the next older generation. Since generation 2 is the oldest generation, objects in that generation remain there after a collection. In order to decide when to run, the collector keeps track of the number object allocations and deallocations since the last collection. When the number of allocations minus the number of deallocations exceeds threshold0, collection starts. Initially only generation 0 is examined. If generation 0 has been examined more than threshold1 times since generation 1 has been examined, then generation 1 is examined as well. Similarly, threshold2 controls the number of collections of generation 1 before collecting generation 2.

参考文档:

Python的垃圾回收机制是以:引用计数器为主,标记清除和分代回收为辅。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值