Is there any performance reason to declare method parameters final in Java?

JavaPerformanceFinal

Java Problem Overview


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().

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

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.

Solution 3 - Java

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

Solution 4 - Java

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

http://mindprod.com/jgloss/final.html

Solution 5 - Java

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKipView Question on Stackoverflow
Solution 1 - JavaRobinView Answer on Stackoverflow
Solution 2 - JavaDobes VandermeerView Answer on Stackoverflow
Solution 3 - Javauser666View Answer on Stackoverflow
Solution 4 - JavabranchgabrielView Answer on Stackoverflow
Solution 5 - Javauser1402866View Answer on Stackoverflow