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.

aurelius
  • 3,946
  • 7
  • 40
  • 73
  • 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 '17 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 '17 at 12:02
  • 1
    @Bathsheba did so – aurelius Jun 23 '17 at 12:02
  • 2
    @M.Navy: the question was asked almost 7 years ago – aurelius Jun 23 '17 at 12:03
  • @sbjavateam: you are right, but if the variable is already final, checkes should not be done anymore – aurelius Jun 23 '17 at 12:05
  • 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 – Oleg Estekhin Jun 23 '17 at 12:07

2 Answers2

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.

apangin
  • 92,924
  • 10
  • 193
  • 247
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.
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Nishant Bhardwaz
  • 924
  • 8
  • 21