为什么将类定义为final会改善JVM性能? [英] Why defining class as final improves JVM performance?

查看:329
本文介绍了为什么将类定义为final会改善JVM性能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

http://sites.google.com/site/gson/引用gson-design-document


为什么Gson中的大多数课程都标记为
final?

Why are most classes in Gson marked as final?

虽然Gson通过提供
可插拔序列化器和
反序列化器提供了相当
可扩展架构,但Gson类不是
专门设计为
b $ b可扩展。提供非最终
类将允许用户以
合法地扩展Gson类,并且
然后期望该行为在
所有后续修订中工作。我们通过将
类标记为final来选择
限制此类用例,并等待
好​​的用例出现以允许
可扩展性。标记类最终
也有一个小好处,即为Java编译器和虚拟机提供
额外的优化机会

While Gson provides a fairly extensible architecture by providing pluggable serializers and deserializers, Gson classes were not specifically designed to be extensible. Providing non-final classes would have allowed a user to legitimately extend Gson classes, and then expect that behavior to work in all subsequent revisions. We chose to limit such use-cases by marking classes as final, and waiting until a good use-case emerges to allow extensibility. Marking a class final also has a minor benefit of providing additional optimization opportunities to Java compiler and virtual machine.

为什么会这样? [如果我猜测:JVM知道类是最终的,它不维护方法覆盖表?还有其他原因吗?]

Why is this the case? [If I would guess: of JVM knows class is final it does not maintain method override tables? Are there any other reasons?]

表现有什么好处?

这是否适用于那些频率实例化(POJO?)或者可能是持有静态方法(实用类)的类?

Does this applies to classes that are frequency instantiated (POJO?) or perhaps to class that are holders static methods (Utility classes) ?

定义为final的方法在理论上也能提高性能吗?

Are methods defined as final also can theoretically improve performance?

是否有任何影响?

谢谢,
Maxim。

Thank you, Maxim.

推荐答案

虚拟(重写)方法通常通过某种表(vtable)实现,该表最终是一个函数指针。每个方法调用都有必须通过该指针的开销。当类被标记为final时,所有方法都不能被覆盖,并且不再需要使用表 - 这更快。

Virtual (overridden) methods generally are implemented via some sort of table (vtable) that is ultimately a function pointer. Each method call has the overhead of having to go through that pointer. When classes are marked final then all of the methods cannot be overridden and the use of a table is not needed anymore - this it is faster.

一些虚拟机(如HotSpot)可以更智能地做事情并知道何时不覆盖方法并在适当时生成更快的代码。

Some VMs (like HotSpot) may do things more intelligently and know when methods are/are not overridden and generate faster code as appropriate.

这里是关于HotSpot的一些更具体的信息。还有一些一般信息。

Here is some more specific info on HotSpot. And some general info too.

这篇关于为什么将类定义为final会改善JVM性能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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