Quantcast
Channel: Baeldung
Viewing all articles
Browse latest Browse all 4536

The Java final Keyword – Impact on Performance

$
0
0

 1. Overview

The performance benefit of using the final keyword is a very popular debate topic among Java developers. Depending on where we apply it, the final keyword can have a different purpose and different performance implications.

In this tutorial, we'll explore if there are any performance benefits from using the final keyword in our code. We'll look at the performance implications of using final on a variable, method, and class level.

Alongside performance, we'll also mention the design aspects of using the final keyword. Finally, we'll recommend whether and for what reason we should use it.

2. Local Variables

When final is applied to a local variable, its value must be assigned exactly once.

We can assign the value in the final variable declaration or in the class constructor. In case we try to change the final variable value later, the compiler will throw an error.

2.1. Performance Test

Let's see if applying the final keyword to our local variables can improve performance.

We'll make use of the JMH tool in order to measure the average execution time of a benchmark method. In our benchmark method, we'll do a simple string concatenation of non-final local variables:

@Benchmark
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@BenchmarkMode(Mode.AverageTime)
public static String concatNonFinalStrings() {
    String x = "x";
    String y = "y";
    return x + y;
}

Next, we'll repeat the same performance test, but this time with final local variables:

@Benchmark
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@BenchmarkMode(Mode.AverageTime)
public static String concatFinalStrings() {
    final String x = "x";
    final String y = "y";
    return x + y;
}

JMH will take care of running warmup iterations in order to let the JIT compiler optimizations kick in. Finally, let's take a look at the measured average performances in nanoseconds:

Benchmark                              Mode  Cnt  Score   Error  Units
BenchmarkRunner.concatFinalStrings     avgt  200  2,976 ± 0,035  ns/op
BenchmarkRunner.concatNonFinalStrings  avgt  200  7,375 ± 0,119  ns/op

In our example, using final local variables enabled 2.5 times faster execution.

2.2. Static Code Optimization

The string concatenation example demonstrates how the final keyword can help the compiler optimize the code statically.

Using non-final local variables, the compiler generated the following bytecode to concatenate the two strings:

NEW java/lang/StringBuilder
DUP
INVOKESPECIAL java/lang/StringBuilder.<init> ()V
ALOAD 0
INVOKEVIRTUAL java/lang/StringBuilder.append (Ljava/lang/String;)Ljava/lang/StringBuilder;
ALOAD 1
INVOKEVIRTUAL java/lang/StringBuilder.append (Ljava/lang/String;)Ljava/lang/StringBuilder;
INVOKEVIRTUAL java/lang/StringBuilder.toString ()Ljava/lang/String;
ARETURN

By adding the final keyword, we helped the compiler conclude that the string concatenation result will actually never change. Thus, the compiler was able to avoid string concatenation altogether and statically optimize the generated bytecode:

LDC "xy"
ARETURN

We should note that most of the time, adding final to our local variables will not result in significant performance benefits as in this example.

3. Instance and Class Variables

We can apply the final keyword to instance or class variables. That way, we ensure that their value assignment can be done only once. We can assign the value upon final instance variable declaration, in the instance initializer block or in the constructor.

A class variable is declared by adding the static keyword to a member variable of a class. Additionally, by applying the final keyword to a class variable, we're defining a constant. We can assign the value upon constant declaration or in the static initializer block:

static final boolean doX = false;
static final boolean doY = true;

Let's write a simple method with conditions that use these boolean constants:

Console console = System.console();
if (doX) {
    console.writer().println("x");
} else if (doY) {
    console.writer().println("y");
}

Next, let's remove the final keyword from the boolean class variables and compare the class generated bytecode:

  • Example using non-final class variables – 76 lines of bytecode
  • Example using final class variables (constants) – 39 lines of bytecode

By adding the final keyword to a class variable, we again helped the compiler to perform static code optimization. The compiler will simply replace all references of final class variables with their actual values.

However, we should note that an example like this one would rarely be used in real-life Java applications. Declaring variables as final can only have a minor positive impact on the performances of real-life applications.

4. Effectively Final

The term effectively final variable was introduced in Java 8. A variable is effectively final if it isn't explicitly declared final but its value is never changed after initialization.

The main purpose of effectively final variables is to enable lambdas to use local variables that are not explicitly declared final. However, the Java compiler won't perform static code optimization for effectively final variables the way it does for final variables.

5. Classes and Methods

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. Moreover, final classes and methods can be a cause of great inconvenience for developers, as they limit our options for reusing existing code. Thus, reckless use of final can compromise good object-oriented design principles.

There are some valid reasons for creating final classes or methods, such as enforcing immutability. However, performance benefit is not a good reason for using final on class and method levels.

6. Performance vs. Clean Design

Besides performance, we might consider other reasons for using final. The final keyword can help improve code readability and understandability. Let's look into a few examples of how final can communicate design choices:

  • final classes are immutable by design
  • methods are declared final to prevent incompatibility of child classes
  • method arguments are declared final to prevent side effects
  • final variables are read-only by design

Thus, we should use final for communicating design choices to other developers. Furthermore, the final keyword applied to variables can serve as a helpful hint for the compiler to perform minor performance optimizations.

7. Conclusion

In this article, we looked into the performance benefits of using the final keyword. In the examples, we showed that applying the final keyword to variables can have a minor positive impact on performance. Nevertheless, applying the final keyword to classes and methods will not result in any performance benefits.

We demonstrated that, unlike final variables, effectively final variables are not used by the compiler for performing static code optimization. Finally, besides performance, we looked at the design implications of applying the final keyword on different levels.

As always, the source code is available over on GitHub.

The post The Java final Keyword – Impact on Performance first appeared on Baeldung.
       

Viewing all articles
Browse latest Browse all 4536

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>