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.