为什么Python同时使用引用计数和标记-清除来进行GC?
我的问题是为什么 python 同时使用引用计数和标记和清除来进行GC?为什么不只是标记和清除?
我最初的猜测是,使用引用计数可以轻松删除非循环引用的对象,这可能会在一定程度上加快标记和清除速度并立即获得内存。不知道我的猜测是否正确?
有什么想法吗?
多谢。
My question is why does python use both reference counting and mark-and-sweep for gc? Why not only mark-and-sweep?
My initial guess is that using reference counting can easily remove non-cyclic referenced objects, this may somewhat speed up mark-and-sweep and gain memory immediately. Don't know if my guess is right?
Any thoughts?
Thanks a lot.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Python(语言)没有说明它使用哪种形式的垃圾收集。主要实现(通常称为 CPython)如您所描述的那样。其他版本(例如 Jython 或 IronPython)使用纯粹的垃圾收集系统。
是的,通过引用计数进行早期收集有一个好处,但 CPython 使用它的主要原因是历史性的。最初没有针对循环对象的垃圾回收,因此循环导致内存泄漏。 C API 和数据结构很大程度上基于引用计数原理。添加真正的垃圾收集后,就无法破坏现有的二进制 API 以及依赖它们的所有库,因此必须保留引用计数。
Python (the language) doesn't say which form of garbage collection it uses. The main implementation (often known as CPython) acts as you describe. Other versions such as Jython or IronPython use a purely garbage collected system.
Yes, there is a benefit of earlier collection with reference counting, but the main reason CPython uses it is historical. Originally there was no garbage collection for cyclic objects so cycles led to memory leaks. The C APIs and data structures are based heavily around the principle of reference counting. When real garbage collection was added it wasn't an option to break the existing binary APIs and all the libraries that depended on them so the reference counting had to remain.
引用计数比垃圾回收更快地释放对象。
但是由于引用计数无法处理无法访问的对象之间的引用循环,因此 Python 使用垃圾收集器(实际上只是一个循环收集器)来收集存在的这些循环。
Reference counting deallocates objects sooner than garbage collection.
But as reference counting can't handle reference cycles between unreachable objects, Python uses a garbage collector (really just a cycle collector) to collect those cycles when they exist.
是的。一旦引用计数变为零,对象就可以被删除。这不会发生在循环引用的对象中。 AFAIK,标记和清除是一项成本高昂的操作,实现它的最简单方法要求您在标记对象时“停止世界”。当遍历完所有对象后,未标记(可达)的 Andy 对象将被释放。
Yes. As soon as the refcount goes to zero and object can be removed. This won't happen in a cyclic referenced object. AFAIK, mark and sweep is a costly operation and the simplest way to implement it requires you to "stop the world" while objects are marked. When all of the objects are traversed, andy object not marked (as reachable) is released.