关于Python垃圾回收机制的问题

关于Python垃圾回收机制的问题

我在某度搜到的一些博客有讲到,Python底层有分代回收的机制,于是我便记下了。可我前些时间面试的时候,说了一下这方面的东西,面试官却反驳我说这是JAVA的回收机制,搞得我半信半疑。现在网络环境确实有点让人拎不清楚,所以想请大佬们给个答复,Python底层是否也有分代回收的机制?


回答:

线索

https://docs.python.org/3/lib...
https://devguide.python.org/g...

官方文档里没有明确提到关键词 Generational GC 一词,但从 gc 模块和开发指导等各种地方都有提到 Generation 的概念。

从第二个链接的内容

In order to limit the time each garbage collection takes, the GC uses a popular optimization: generations. The main idea behind this concept is the assumption that most objects have a very short lifespan and can thus be collected shortly after their creation. This has proven to be very close to the reality of many Python programs as many temporarily objects are created and destroyed very fast. The older an object is the less likely it is that it will become unreachable.

可以比较明确地看出是分代 GC 的思想。

再深入 Python 源码,在 Modules/gcmodule.c 的开头几行注释里就提到了这个文档

http://www.arctrix.com/nas/py...

Generational collection works (currently three generations). The overhead measured by pybench is about 4 percent. Virtually all extension modules should work unchanged (I had to modify new and cPickle in the standard distribution). A new module called gc is available for tuning the collector and setting debugging options.

文档发布的日期是 2000 年,早期邮件列表内容没有出现在 python.org 官网的文档里,很正常。从源码的注释里还是能找到相关的讨论历史的。

总结

Q: Python 有分代 GC 吗?
A: 有,很早就有,和引用计数共存。见上文链接。

Since we are still using reference counting, the garbage collector only has to find reference cycles.

Q: Python 的分代 GC 和 Java 的分代 GC 是一回事吗?
A: 指导思想类似,但不能当做一回事。

以上是 关于Python垃圾回收机制的问题 的全部内容, 来源链接: utcz.com/p/937993.html

回到顶部