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

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

问题描述

有效的 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 只需要复制那些仍然活着"到更永久的存储空间,然后它可以一次擦除(释放)整个伊甸园"内存块.这是有效的,因为大多数 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.

所有这些因素加起来都会导致显着的运行时损失,这就是为什么通常首选确定性终结(使用 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天全站免登陆