views:

2005

answers:

4

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

+1  A: 

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

mugafuga
The question was about parameters being declared final, which has no performance impact.
Robin
On modern JIT'S (Hotspot) final does not have any (measurable) performance influence at all, whether applied to parameters or the class
kohlerm
+1  A: 

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 :)

Mike Blandford
+3  A: 

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.

Dobes Vandermeer
+9  A: 

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.

Check here for final on methods

Robin
you'd think that final variables/params could be optimized as loop variables though...but a good compiler/runtime should be able to figure that out without final anyway...
John Gardner