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

查看:33
本文介绍了在 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 字段,值得一提的是,无论如何,就清晰的设计而言,它们通常是一个好主意.它们还更改了跨线程可见性方面的保证行为:在构造函数完成后,任何 final 字段都保证立即在其他线程中可见.根据我的经验,这可能是 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天全站免登陆