好的,我已经编写了一个微基准测试(如@Joni和@MattBall所建议的那样),以下是每个本地变量和实例变量的1 x 1000000000次访问的结果:
Average time for instance variable access: 5.08E-4
Average time for local variable access: 4.96E-4
对于每个 10 x 1000000000 次访问:
Average time for instance variable access:4.723E-4
Average time for local variable access:4.631E-4
对于每个 100 x 10000000000 次访问:
Average time for instance variable access: 5.050300000000002E-4
Average time for local variable access: 5.002400000000001E-4
因此,局部变量访问似乎确实比实例 var 访问更快(即使两者都指向同一对象)。
注意:我不想找出来,因为我想优化一些东西,这只是纯粹的兴趣。
附言:这是微基准测试的代码:
public class AccessBenchmark {
private final long N = 1000000000;
private static final int M = 1;
private LocalClass instanceVar;
private class LocalClass {
public void someFunc() {}
}
public double testInstanceVar() {
// System.out.println("Running instance variable benchmark:");
instanceVar = new LocalClass();
long start = System.currentTimeMillis();
for (int i = 0; i < N; i++) {
instanceVar.someFunc();
}
long elapsed = System.currentTimeMillis() - start;
double avg = (elapsed * 1000.0) / N;
// System.out.println("elapsed time = " + elapsed + "ms");
// System.out.println(avg + " microseconds per execution");
return avg;
}
public double testLocalVar() {
// System.out.println("Running local variable benchmark:");
instanceVar = new LocalClass();
LocalClass localVar = instanceVar;
long start = System.currentTimeMillis();
for (int i = 0 ; i < N; i++) {
localVar.someFunc();
}
long elapsed = System.currentTimeMillis() - start;
double avg = (elapsed * 1000.0) / N;
// System.out.println("elapsed time = " + elapsed + "ms");
// System.out.println(avg + " microseconds per execution");
return avg;
}
public static void main(String[] args) {
AccessBenchmark bench;
double[] avgInstance = new double[M];
double[] avgLocal = new double[M];
for (int i = 0; i < M; i++) {
bench = new AccessBenchmark();
avgInstance[i] = bench.testInstanceVar();
avgLocal[i] = bench.testLocalVar();
System.gc();
}
double sumInstance = 0.0;
for (double d : avgInstance) sumInstance += d;
System.out.println("Average time for instance variable access: " + sumInstance / M);
double sumLocal = 0.0;
for (double d : avgLocal) sumLocal += d;
System.out.println("Average time for local variable access: " + sumLocal / M);
}
}