I've seen this thread: Speed of if compared to conditional
Made my own class for checking the speed
public class Question {
static long startTime;
static long elapsedTime;
static String mStatic;
private String mPublic;
public static void main(String[] args) {
Question q = new Question();
q.executeGlobal();
q.executeStatic();
q.executeLocal();
}
public void executeLocal() {
String mLocal;
startTime = System.nanoTime();
for (int i = 0; i < 1000000000; i++) {
mLocal = "";
}
elapsedTime = System.nanoTime() - startTime;
System.out.println("Type Local: " + elapsedTime + " ns");
}
public void executeGlobal() {
startTime = System.nanoTime();
for (int i = 0; i < 1000000000; i++) {
mPublic = "";
}
elapsedTime = System.nanoTime() - startTime;
System.out.println("Type Global: " + elapsedTime + " ns");
}
public void executeStatic() {
startTime = System.nanoTime();
for (int i = 0; i < 1000000000; i++) {
mStatic = "";
}
elapsedTime = System.nanoTime() - startTime;
System.out.println("Type Static: " + elapsedTime + " ns");
}
}
Result:
Type Global: 45693028 ns
Type Static: 43853723 ns
Type Local: 2057505 ns
In the answer @Rod_algonquin answered that it is because of the getstatic/putstatic bytecode for static variable and getfield/putfield bytecode for the member variable, that it is calculating through bit-shifting and some addition.
At first I thought that only Objects causes this, but upon trying to reference primitive the result is the same local variable
is still faster.
Why is that local variable is faster? except the bytecode explanation.