简体   繁体   中英

Does the Java static modifier have a positive effect 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 static modifier on the variable b and on the method computeB() have any positive performance effects on runtime on the JVM?

Like most of these questions you should consider clarity first, and performance a distant second. Make the code clear and simple and it is likely to perform reasonably well.

In terms of clarity, the main advantage is making it clear you are not using this in the method. This can make it easier to refactor the method.

As @OceanLife mentions, using mutable static fields should be avoided. Static fields are like singletons, and they are harder to unit test and to make thread safe.

While I would make methods static where possible, I would avoid using static fields unless they are immutable.

using static on a method has two notional performance advantages

  • it means one less object is passed on the stack.
  • it can't be overridden so it is not "virtual"

In reality the JIT can optimise away most of the differences but since your code is being run enough to be optimised it can make a small difference.

BTW running your code enough to be optimised will make much, much more difference.

I haven't attempted any benchmarking of this scenario but use of the static keyboard (notably when developing with Java ME/Android) has a positive effect on performance. Some estimates discuss a 20% execution speed boost owing to inlining and the subsequent re-JIT'ing after the so-called 'warm-up' period.

That said, stateful static methods are bad. Recently, heavy weigh Google/Square devs have been discussing this with the wider community .

If you compare what invokestatic jvm instruction does compared to invokevirtual or invokeinterface , you can see that invokestatic should be faster. Compared with invokevirtual, method is only looked up in the static method list (smaller) and class hierarchy is ignored. invokeinterface does even more work since it cannot optimize the method lookup (and thus is the slowest of them all).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM