为什么Java和Python垃圾收集方法有所不同? [英] Why Java and Python garbage collection methods are different?

查看:79
本文介绍了为什么Java和Python垃圾收集方法有所不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python使用引用计数方法来处理对象的生命周期。因此,一个没有更多用途的对象将被立即销毁。



但是,在Java中,GC(垃圾回收器)销毁在特定时间不再使用的对象。



为什么Java选择这种策略以及从中获益?

Python的方法?

解决方案

使用引用计数有一些缺点。其中提到的最多的是循环引用:假设引用B,B引用C和C引用B.如果A将它的引用放到B中,那么B和C都将具有1的引用计数并且不会被删除与传统的参考计数。 CPython(引用计数不是python本身的一部分,但是它的C实现的一部分)通过一个单独的垃圾收集例程来捕获循环引用,它会定期运行...



另一个缺点:引用计数会使执行速度变慢。每次引用和取消引用对象时,解释器/虚拟机都必须检查计数是否降到0(然后如果是,则释放)。垃圾收集不需要这样做。



另外,垃圾收集可以在单独的线程中完成(尽管它可能有点棘手)。在拥有大量RAM的机器上,以及只能缓慢使用内存的进程中,您可能根本不想进行GC操作!在性能方面,引用计数会有点缺点......

Python uses the reference count method to handle object life time. So an object that has no more use will be immediately destroyed.

But, in Java, the GC(garbage collector) destroys objects which are no longer used at a specific time.

Why does Java choose this strategy and what is the benefit from this?

Is this better than the Python approach?

解决方案

There are drawbacks of using reference counting. One of the most mentioned is circular references: Suppose A references B, B references C and C references B. If A were to drop its reference to B, both B and C will still have a reference count of 1 and won't be deleted with traditional reference counting. CPython (reference counting is not part of python itself, but part of the C implementation thereof) catches circular references with a separate garbage collection routine that it runs periodically...

Another drawback: Reference counting can make execution slower. Each time an object is referenced and dereferenced, the interpreter/VM must check to see if the count has gone down to 0 (and then deallocate if it did). Garbage Collection does not need to do this.

Also, Garbage Collection can be done in a separate thread (though it can be a bit tricky). On machines with lots of RAM and for processes that use memory only slowly, you might not want to be doing GC at all! Reference counting would be a bit of a drawback there in terms of performance...

这篇关于为什么Java和Python垃圾收集方法有所不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆