javaperformancefinal

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


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


Solution

  • 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.