Does Use of Final Keyword in Java Improve the Performance

Does use of final keyword in Java improve the performance?

Usually not. For virtual methods, HotSpot keeps track of whether the method has actually been overridden, and is able to perform optimizations such as inlining on the assumption that a method hasn't been overridden - until it loads a class which overrides the method, at which point it can undo (or partially undo) those optimizations.

(Of course, this is assuming you're using HotSpot - but it's by far the most common JVM, so...)

To my mind you should use final based on clear design and readability rather than for performance reasons. If you want to change anything for performance reasons, you should perform appropriate measurements before bending the clearest code out of shape - that way you can decide whether any extra performance achieved is worth the poorer readability/design. (In my experience it's almost never worth it; YMMV.)

EDIT: As final fields have been mentioned, it's worth bringing up that they are often a good idea anyway, in terms of clear design. They also change the guaranteed behaviour in terms of cross-thread visibility: after a constructor has completed, any final fields are guaranteed to be visible in other threads immediately. This is probably the most common use of final in my experience, although as a supporter of Josh Bloch's "design for inheritance or prohibit it" rule of thumb, I should probably use final more often for classes...

Does declaring variables as final, inside methods, improve performance?

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.

Use of final keyword in Java method performance?

Theoretically, declaring a parameter final is not going to make a difference: the compiler is allowed to be smart enough to figure out that your method does not change the limit parameter, and optimize the code that it generates as if the parameter were declared final without the actual declaration.

The biggest difference that you are going to get by declaring method parameter final is the ability to reference that parameter in anonymous classes.

Another useful consequence is that people who maintain your code after you would know that keeping that parameter unchanged was your conscious decision, not a coincidence.

Does the keyword final have any impact on the JVM?

IBM states:

Like many myths about Java performance, the erroneous belief that declaring classes or methods as final results in better performance is widely held but rarely examined. The argument goes that declaring a method or class as final means that the compiler can inline method calls more aggressively, because it knows that at run time this is definitely the version of the method that's going to be called. But this is simply not true. Just because class X is compiled against final class Y doesn't mean that the same version of class Y will be loaded at run time. So the compiler cannot inline such cross-class method calls safely, final or not. Only if a method is private can the compiler inline it freely, and in that case, the final keyword would be redundant.

Java final performance/optimization

If something can never change, you can do all kinds of optimizations like in-lining of the actual value instead of looking it up over and over again. This is just one thing you can do that is easy to explain and gives the greatest benefit.

There are many other more esoteric things that happen that have much less impact.

If you look at the bytecode you will see this, especially after the JIT kicks in.

Making the entire class final can have similar benefits.

That said, final references will not always provide measurable
gains, it depends on the usage of the reference. In this case
EnumSet does a lot of special sauce stuff under the hood if you look
at the source. Immutable references probably get inlined as part of
that.

Also note that the behavior you are seeing might go away in future release of the JVM, or not be there in other JVM implementations. Anything is subject to change out from under you so don't rely on any one specific implementation.

Here is some more information in greater detail about all the idiomatic uses of final.

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

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.

How final keyword improves the performance? (memory wise or speed wise)

No usually... using just final will not improve the performance, Most of the times it use to avoid/achieve following things.

final keyword

  • Which is used to
    stop method overriding
  • and to stop re assigning the value which is already initialized , means the if the variable is final it cant be initialized
  • A final class is simply a class that can't be extended , means which cannot become a super class

static keyword

  • The static variable can be used to refer the common property of all
    objects (that is not unique for each object) e.g. company name of
    employees,college name of students etc.
  • In other words The static keyword denotes that a member variable, or
    method, can be accessed without requiring an instantiation of the
    class to which it belongs.
  • The static variable gets memory only once in class area at the time of class loading.

static and final together

  • Declaring variables only as static can lead to change in their values
    by one or more instances of a class in which it is declared.
  • Declaring them as static final will help you to create a CONSTANT.
    Only one copy exists which can be accessed anywhere

Are the effectively final variables interpreted as final by compiler in Java 8?

Does compiler in java 8 interpret effectively final variables as final variables and later, in runtime use it as final?

The answer will be yes in both cases.

The reason for the latter is that the class file format does not provide a way to say whether a local variable is declared as final. Therefore, if the JIT compiler is going to optimize based on finality, the finality must be inferred from what the bytecodes of a method actually do; i.e. effective finality.

Do java finals help the compiler create more efficient bytecode?

The bytecodes are not significantly more or less efficient if you use final because Java bytecode compilers typically do little in the way optimization. The efficiency bonus (if any) will be in the native code produced by the JIT compiler1.

In theory, using the final provides a hint to the JIT compiler that should help it optimize. In practice, recent HotSpot JIT compilers can do a better job by ignoring your hints. For instance, a modern JIT compiler typically performs a global analysis to find out if a given method call is a call to a leaf method in the context of the application's currently loaded classes. This analysis is more accurate than your final hints can be, and the runtime can even detect when a new class is loaded that invalidates the analysis ... and redo the analysis and native code generation for the affected code.

There are other semantic consequences for use of final:

  • Declaring a variable as final stops you from accidentally changing it. (And expresses your intention to the reader.)
  • Declaring a method as final prevents overriding in a subclass.
  • Declaring a class as final prevents subclassing entirely.
  • Declaring a field as final stops a subclass from changing it.
  • Declaring a field as final has important consequences for thread-safety; see JLS 17.5.

In the right circumstances, these can all be good. However, it is clear that they limit your options for reuse by creating subclasses. This needs to be considered when deciding whether or not to use final.

So good practice is to use final to (broadly speaking) express your design intentions, and to achieve other semantic effects that you require. If you use final solely as an optimization hint, you won't achieve much.


There are a couple of exceptions where final could lead to small performance improvements on some platforms.

  • Under certain circumstances, declaring a field as final changes the way that the bytecode compiler deals with it. I've given one example above. Another is the "constant variable" case (JLS 4.12.4) where a static final field's value will be inlined by the bytecode compiler both in the current classes, and in other classes, and this may affect the observed behavior of code. (For example, referring to a constant variable will NOT trigger class initialization. Hence, the addition of a final may change the order of class initialization.)

  • It is conceivable that declaring a field or local parameter as final may allow minor JIT compiler optimization that wouldn't otherwise be done. However, any field that can be declared as final could also be inferred to be effectively final by the JIT compiler. (It is just not clear that the JIT compiler actually does this, and whether that affects the generated native code.)

However the bottom line remains the same. You should use final to express your design intentions, not as an optimization hint.


1 - This answer assumes that we are talking about a recent JVM with a good JIT or AOT compiler. 1) The earliest Sun Java implementations didn't have a JIT compiler at all. 2) Early Android Java implementations had compilers which did a poor job of optimizing. Indeed the early Android developer documentation advised various source-level micro-optimizations to compensate. This advice has since been removed.



Related Topics



Leave a reply



Submit