Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does declaring variables as final, inside methods, improve performance? [duplicate]

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.

like image 869
aurelius Avatar asked Jun 23 '17 11:06

aurelius


People also ask

Does adding final improve performance?

The final keyword has a different purpose when applied to classes and methods. When we apply the final keyword to a class, then that class cannot be subclassed. When we apply it to a method, then that method cannot be overridden. There are no reported performance benefits of applying final to classes and methods.

What are the performance benefits of making a method as final?

Making a class, method, or variable final in Java helps to improve performance because JVM gets an opportunity to make assumptions and optimization.

What is the purpose of declaring a variable as final?

Final variables If a variable is declared with the final keyword, its value cannot be changed once initialized. Note that the variable does not necessarily have to be initialized at the time of declaration.

Should method variables be final?

Method parameters and local variables should not be declared final unless it improves readability or documents an actual design decision. Fields should be declared final unless there is a compelling reason to make them mutable.


2 Answers

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.

like image 88
apangin Avatar answered Sep 24 '22 08:09

apangin


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.
like image 25
Nishant Bhardwaz Avatar answered Sep 24 '22 08:09

Nishant Bhardwaz