在Java中将方法参数声明为final是否有任何性能原因?

发布于 2024-07-08 14:30:34 字数 247 浏览 5 评论 0原文

在Java中将方法参数声明为final是否有任何性能原因?

如:

public void foo(int bar) { ... }

对比:

public void foo(final int bar) { ... }

假设 barfoo() 中仅被读取且从未被修改。

Is there any performance reason to declare method parameters final in Java?

As in:

public void foo(int bar) { ... }

Versus:

public void foo(final int bar) { ... }

Assuming that bar is only read and never modified in foo().

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

橘味果▽酱 2024-07-15 14:30:34

局部变量和参数的类文件中不会出现final关键字,因此不会影响运行时性能。 它的唯一用途是澄清编码人员不更改变量的意图(许多人认为其使用原因可疑),并处理匿名内部类。

关于方法本身的 Final 修饰符是否具有任何性能增益存在很多争论,因为无论如何修饰符如何,优化编译器都会在运行时内联这些方法。 在这种情况下,它也应该仅用于限制方法的重写。

The final keyword does not appear in the class file for local variables and parameters, thus it cannot impact the runtime performance. It's only use is to clarify the coders intent that the variable not be changed (which many consider dubious reason for its usage), and dealing with anonymous inner classes.

There is a lot of argument over whether the final modifier on the method itself has any performance gain since the methods will be inlined by the optimizing compiler at runtime anyway, regardless of the modifier. In this case it should also only be used to restrict the overriding of the method.

逆夏时光 2024-07-15 14:30:34

最终参数的唯一好处是它可以在匿名嵌套类中使用。 如果参数从未更改,即使没有最终修饰符,编译器也会将其检测为正常操作的一部分。 由意外分配的参数引起的错误非常罕见 - 如果您的方法足够大,需要这种级别的工程,请将它们缩小 - 您调用的方法无法更改您的参数。

The only benefit to a final parameter is that it can be used in anonymous nested classes. If a parameter is never changed, the compiler will already detect that as part of its normal operation even without the final modifier. It's pretty rare that bugs are caused by a parameter being unexpectedly assigned - if your methods are big enough to need this level of engineering, make them smaller - methods you call can't change your parameters.

爱给你人给你 2024-07-15 14:30:34

在类加载后运行的编译器(例如 JIT 编译器)可以利用 Final 方法。 因此,声明为最终的方法可能会带来一些性能优势。

http://www.javaperformancetuning.com/tips/final.shtml

哦还有另一个好资源

http://mindprod.com/jgloss/final.html

Compilers that operate after class loading, such as JIT compilers, can take advantage of final methods. Consequently, methods declared final could have some performance benefit.

http://www.javaperformancetuning.com/tips/final.shtml

Oh and another good resource

http://mindprod.com/jgloss/final.html

温柔一刀 2024-07-15 14:30:34

与上面使用在方法内声明的非最终局部变量相比,还有一点需要注意的是,内部类实例可能比堆栈帧寿命更长,因此当内部对象仍然存在时,局部变量可能会消失

Just one more point that to above that using non-final local variables declared within the method—the inner class instance may outlive the stack frame, so the local variable might vanish while the inner object is still alive

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文