9

Does declaring variables as final inside a method brings any benefit from a performance/memory point of view in the latest java versions?

I am not talking here about any other benefit.

This question Does use of final keyword in Java improve the performance? was addresed almost 7 years ago, some progress has been done since then.

6
  • 2
    Interesting. The initial reaction is to say "of course not, have a downvote". But this has depth: have Java compilers got clever enough to make optimisations based on this? Are there any that can be made? Have an upvote instead! (I'd consider removing the memory tag though, and substituting performance).
    – Bathsheba
    Jun 23, 2017 at 11:58
  • 3
    starting in Java SE 8, variable or parameter whose value is never changed after it is initialized is effectively final , also JIT can do some optimization with final or effectively final variables
    – xyz
    Jun 23, 2017 at 12:02
  • 1
    @Bathsheba did so
    – aurelius
    Jun 23, 2017 at 12:02
  • 2
    @M.Navy: the question was asked almost 7 years ago
    – aurelius
    Jun 23, 2017 at 12:03
  • 2
    @aurelius so what? instead of creating a duplicate, add a bounty to the existing question with a reason like "i would like to get the latest data available on that topic" or whatever Jun 23, 2017 at 12:07

2 Answers 2

3

No, final keyword on a local variable has no performance impact, and it cannot have even in theory, since .class files do not retain this information.

See this answer for details.

2

final keyword has no direct performance impact if we will talk about variables, but can improve performance in some use cases.
Example:

  1. When iterating in a loop, if the variable is final then JIT will not check for any cause which can change the value of the list (reference).
  2. final allows a variable to be inlined into the calling code, so that could cause some memory and performance improvement. This is used when you have a number of public static final Strings in a class (reference).
  3. final keyword improves performance. Not just JVM can cache final variable but also application can cache frequently use final variables (check here for 3 and 4).
  4. final keyword allows JVM to optimized method, variable or class.
1
  • please provide the usecases in your post and you'll have my upvote
    – aurelius
    Jun 23, 2017 at 16:58

Not the answer you're looking for? Browse other questions tagged or ask your own question.