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()
.
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()
.
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
I can't think of a reason why the compiler would care if you declared a method parameter final or not.
But the real answer to this question is - write two functions, one with final parameters and one with regular parameters. Run them a million times each and see if there's any noticeable runtime difference.
If you're worried about performance, it's very important to do some profiling work on your code and find out exactly what is slowing you down. It's almost certainly not what you would expect it to be :)
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 it's 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.
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.