为什么终结器会有“严重的性能损失”? [英] Why do finalizers have a "severe performance penalty"?

查看:136
本文介绍了为什么终结器会有“严重的性能损失”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Effective Java说:

Effective Java says :


使用终结器会有严重的性能损失。

There is a severe performance penalty for using finalizers.

为什么使用终结器销毁对象的速度较慢?

Why is it slower to destroy an object using the finalizers?

推荐答案

因为垃圾收集器的工作方式。为了提高性能,大多数Java GC使用复制收集器,其中短期对象被分配到eden内存块中,当需要收集该对象的生成时,GC只需要复制那些对象。对于更永久的存储空间仍然活着,然后它可以立即擦除(释放)整个eden内存块。这是有效的,因为大多数Java代码将创建数千个对象实例(盒装基元,临时数组等),生命周期只有几秒钟。

Because of the way the garbage collector works. For performance, most Java GCs use a copying collector, where short-lived objects are allocated into an "eden" block of memory, and when the it's time for that generation of objects to be collected, the GC just needs to copy the objects that are still "alive" to a more permanent storage space, and then it can wipe (free) the entire "eden" memory block at once. This is efficient because most Java code will create many thousands of instances of objects (boxed primitives, temporary arrays, etc.) with lifetimes of only a few seconds.

当你但是,在混合中使用终结器时,GC不能简单地一次擦除整个一代。相反,它需要弄清楚那一代中需要最终确定的所有对象,并将它们排队到实际执行终结器的线程上。与此同时,GC无法有效地清理对象。因此要么让它们保持活动的时间超过它们应该的时间,要么它必须延迟收集其他物体,或两者兼而有之。另外,你有实际执行终结器的任意等待时间。

When you have finalizers in the mix, though, the GC can't simply wipe an entire generation at once. Instead, it needs to figure out all the objects in that generation that need to be finalized, and queue them on a thread that actually executes the finalizers. In the meantime, the GC can't finish cleaning up the objects efficiently. So it either has to keep them alive longer than they should be, or it has to delay collecting other objects, or both. Plus you have the arbitrary wait time of actually executing the finalizers.

所有这些因素加起来都会导致严重的运行时间损失,这就是确定性终结(使用<$ c)的原因$ c> close()方法或类似于显式确定对象的状态)通常是首选。

All these factors add up to a significant runtime penalty, which is why deterministic finalization (using a close() method or similar to explicitly finalize the object's state) is usually preferred.

这篇关于为什么终结器会有“严重的性能损失”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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