为什么将类定义为

为什么将类定义为

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

问题描述

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

为什么 Gson 中的大多数类都标记为最后?

虽然 Gson 提供了一个公平的通过提供可扩展的架构可插拔序列化程序和反序列化器,Gson 类不是专门设计为可扩展.提供非最终类将允许用户合法地扩展 Gson 类,以及然后期望该行为起作用所有后续修订.我们选择了通过标记来限制此类用例类作为最终,并等待直到好的用例出现以允许可扩展性.标记班级决赛也有一个次要的好处是提供额外的优化机会到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 知道 class 是 final 它不维护方法覆盖表吗?还有其他原因吗?]

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?

有什么影响吗?

谢谢,马克西姆.

推荐答案

虚拟(覆盖)方法通常通过某种表(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 性能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 23:47