Does Java static modifier have a positive impact on runtime performance?

public class A {
    private int a;
    private static int b;

    public A(int num) {
        this.a = num;
        this.b = num;

        // which one is quickest?
        this.computeA();
        this.computeB();
    }

    public int computeA() {
        return this.a * this.a;
    }

    public static int computeB() {
        return b * b;
    }
}

      

In the code above, does the modifier static

for the variable b

and method computeB()

have any positive performance effects at runtime on the JVM?

+3


source to share


3 answers


As with most of these questions, you have to consider clarity first and performance in the distant second. Keep the code clear and simple and it will probably work well enough.

In terms of clarity, the main benefit is to make it clear what you are not using this

in the method. This can make method refactoring easier.

As @OceanLife mentions, you should avoid using mutable static fields. Static fields are like single fields, and are harder to unit test and make stream safe.

While I have used methods static

where possible, I would avoid using fields static

unless they are immutable.



using static

by method has two conditional performance advantages

  • this means that another object is being passed on the stack.
  • it cannot be overridden, so it is not "virtual"

In reality, the JIT can optimize most of the differences, but since your code works enough to be optimized, it can make a small difference.

By the way, your code sufficient for optimization will differ significantly.

+5


source


I haven't tried to benchmark this scenario, but using a keyboard static

(especially when developing with Java ME / Android) has a positive impact on performance. Some evaluations discuss a 20% improvement in execution speed due to embedding and then re-JIT'ing after a so-called "warm-up period".



However, legacy static methods are bad. Lately, the heavyweights of Google / Square developers have been discussing this with the wider community .

+1


source


If you are comparing what the invokestatic jvm instruction does versus invokevirtual or invokeinterface , you can see that invokestatic should be faster. Compared to invokevirtual, the method is only seen in the list of static methods (less) and the class hierarchy is ignored. invokeinterface does even more work as it cannot optimize the method lookup (and therefore the slowest one).

0


source







All Articles