问题描述
在方法参数中使用 final
是否允许编译器或运行时环境更快地工作?例如,如果你有一个变量传递给一个你知道不会被修改并被使用的方法,它是更有效的声明它 final
?
示例:
第一个方法应该比第二个方法更快
public int isLargerAfterTripledFaster(int num,final int limit){
num * = 3;
return(num> limit);
}
public int isLargerAfterTripled(int num,int limit){
num * = 3;
return(num> limit);
}
如果我确定我永远不会在这里传递一个可修改的变量,
理论上,声明一个参数 final
不会有什么区别:编译器允许足够聪明,以确定您的方法不会更改 limit
参数,并优化它生成的代码如果参数被声明为 final
而没有实际的声明。
你将通过声明获得最大的区别方法参数 final
是在匿名类中引用该参数的能力。
另一个有用的结果是,你的代码之后你会知道保持该参数不变是你的有意识的决定,而不是巧合。
Does the use final
in method arguments allow the compiler oor runtime environment to work faster? For example, if you have a variable to pass to a method that you know will not be modified and be used as is, is it more efficient to declare it final
?
Example:The first method should be faster than the second method
public int isLargerAfterTripledFaster(int num, final int limit) {
num *= 3;
return (num > limit);
}
public int isLargerAfterTripled(int num, int limit) {
num *= 3;
return (num > limit);
}
If I can be sure I will never want to pass a modifiable variable here, should I do this technique?
Theoretically, declaring a parameter final
is not going to make a difference: the compiler is allowed to be smart enough to figure out that your method does not change the limit
parameter, and optimize the code that it generates as if the parameter were declared final
without the actual declaration.
The biggest difference that you are going to get by declaring method parameter final
is the ability to reference that parameter in anonymous classes.
Another useful consequence is that people who maintain your code after you would know that keeping that parameter unchanged was your conscious decision, not a coincidence.
这篇关于在Java方法性能中使用final关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!