为什么Python同时使用引用计数和标记-清除来进行GC?

发布于 2024-12-29 11:56:00 字数 160 浏览 2 评论 0原文

我的问题是为什么 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

短暂陪伴 2025-01-05 11:56:00

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.

烟织青萝梦 2025-01-05 11:56:00

引用计数比垃圾回收更快地释放对象。

但是由于引用计数无法处理无法访问的对象之间的引用循环,因此 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.

冰魂雪魄 2025-01-05 11:56:00

我最初的猜测是,使用引用计数可以轻松删除非循环引用的对象,这可能会在一定程度上加快标记和清除速度并立即获得内存。不知道我的猜测是否正确?

是的。一旦引用计数变为零,对象就可以被删除。这不会发生在循环引用的对象中。 AFAIK,标记和清除是一项成本高昂的操作,实现它的最简单方法要求您在标记对象时“停止世界”。当遍历完所有对象后,未标记(可达)的 Andy 对象将被释放。

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?

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文