在 Java 中声明方法参数 final 是否有任何性能原因? [英] Is there any performance reason to declare method parameters final in Java?

查看:33
本文介绍了在 Java 中声明方法参数 final 是否有任何性能原因?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

如:

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

对比:

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

假设 barfoo() 中只被读取,从不修改.

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

推荐答案

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.

这篇关于在 Java 中声明方法参数 final 是否有任何性能原因?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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