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()
.
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.
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.
Just one more point that to above that using non-final local variables declared within the method—the inner class instance may outlive the stack frame, so the local variable might vanish while the inner object is still alive
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 assume the compiler could possibly remove all private static final variables that has a primitive type, such as int, and inline them directly in the code just like with a C++ macro.
However, i have no clue if this is done in practice, but it could be done in order to save some memory.