Reputation: 923
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?
Upvotes: 3
Views: 313
Reputation: 6472
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.
Upvotes: 1
Reputation: 533462
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
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.
Upvotes: 6
Reputation: 251
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).
Upvotes: 0