在Java中使用final关键字可以提高性能吗? [英] Does use of final keyword in Java improve the performance?

查看:455
本文介绍了在Java中使用final关键字可以提高性能吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,我们看到很多地方可以使用 final 关键字,但它的使用并不常见。

In Java we see lots of places where the final keyword can be used but its use is uncommon.

例如:

String str = "abc";
System.out.println(str);

在上述情况下, str 可以是 final 但通常不会这样做。

In the above case, str can be final but this is commonly left off.

当一个方法永远不会被覆盖时,我们可以使用final关键字。类似地,如果一个类不会被继承。

When a method is never going to be overridden we can use final keyword. Similarly in case of a class which is not going to be inherited.

在任何或所有这些情况下使用final关键字是否真的能提高性能?如果是这样,那怎么样?请解释。如果正确使用 final 对性能有用,那么Java程序员应该养成哪些习惯来充分利用关键字?

Does the use of final keyword in any or all of these cases really improve performance? If so, then how? Please explain. If the proper use of final really matters for performance, what habits should a Java programmer develop to make best use of the keyword?

推荐答案

通常不是。对于虚方法,HotSpot会跟踪该方法是否已实际被覆盖,并且能够执行优化,例如在假设上内联尚未覆盖方法 - 直到它加载一个覆盖该方法的类,此时它可以撤消(或部分撤消)这些优化。

Usually not. For virtual methods, HotSpot keeps track of whether the method has actually been overridden, and is able to perform optimizations such as inlining on the assumption that a method hasn't been overridden - until it loads a class which overrides the method, at which point it can undo (or partially undo) those optimizations.

(当然,这假设你是使用HotSpot - 但它是迄今为止最常见的JVM,所以...)

(Of course, this is assuming you're using HotSpot - but it's by far the most common JVM, so...)

我想你应该使用 final 基于清晰的设计和可读性而不是出于性能原因。如果您出于性能原因想要更改任何内容,则应在将最清晰的代码变形之前执行适当的测量 - 这样您就可以决定是否所获得的额外性能值得更差的可读性/设计。 (根据我的经验,它几乎永远不值得; YMMV。)

To my mind you should use final based on clear design and readability rather than for performance reasons. If you want to change anything for performance reasons, you should perform appropriate measurements before bending the clearest code out of shape - that way you can decide whether any extra performance achieved is worth the poorer readability/design. (In my experience it's almost never worth it; YMMV.)

编辑:由于已经提到了最后的字段,所以值得提出的是,无论如何它们通常都是个好主意,在清晰的设计方面。它们还在跨线程可见性方面改变了保证行为:在构造函数完成之后,任何最终字段都保证在其他线程中立即可见。根据我的经验,这可能是 final 最常见的用法,虽然作为Josh Bloch的继承设计或禁止它的设计的支持者,我应该使用 final 更常用于课程......

As final fields have been mentioned, it's worth bringing up that they are often a good idea anyway, in terms of clear design. They also change the guaranteed behaviour in terms of cross-thread visibility: after a constructor has completed, any final fields are guaranteed to be visible in other threads immediately. This is probably the most common use of final in my experience, although as a supporter of Josh Bloch's "design for inheritance or prohibit it" rule of thumb, I should probably use final more often for classes...

这篇关于在Java中使用final关键字可以提高性能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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