This question already has an answer here:
-
Does use of final keyword in Java improve the performance?
12 answers
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.
The current java compilers do already a good data flow analysis, it is a statement of having a non-alterable parameter. Only dumb compilers could have some use for this.
For a reader however it is a good hint. And code is written once, read often.
In general it is enforced by some style guides, saying "a parameter should never be overwritten".
A better reason is the usage in an inner class, as there the method context requires parameters and local variables to be final.
However a final method; one that cannot be overriden has optimizing potential.
public final int isLargerAfterTripled(int num, int limit) { ... }
The compiler may inline the function code, as the method will never be overriden.
final
has absolutely no impact on performance. The JIT compiler does not consider final at all.
Also take a look at Brian Goetz's article on Java final.