我正在进行一些测试,以了解使用getter/setter和直接字段访问之间的速度差异。我编写了一个简单的基准应用程序:
public class FieldTest {
private int value = 0;
public void setValue(int value) {
this.value = value;
}
public int getValue() {
return this.value;
}
public static void doTest(int num) {
FieldTest f = new FieldTest();
// test direct field access
long start1 = System.nanoTime();
for (int i = 0; i < num; i++) {
f.value = f.value + 1;
}
f.value = 0;
long diff1 = System.nanoTime() - start1;
// test method field access
long start2 = System.nanoTime();
for (int i = 0; i < num; i++) {
f.setValue(f.getValue() + 1);
}
f.setValue(0);
long diff2 = System.nanoTime() - start2;
// print results
System.out.printf("Field Access: %d ns\n", diff1);
System.out.printf("Method Access: %d ns\n", diff2);
System.out.println();
}
public static void main(String[] args) throws InterruptedException {
int num = 2147483647;
// wait for the VM to warm up
Thread.sleep(1000);
for (int i = 0; i < 10; i++) {
doTest(num);
}
}
}
每次我运行它时,都会得到如下一致的结果:http://pastebin.com/hcAtjVCL 我想知道为什么字段访问似乎比getter / setter方法访问要慢,以及为什么最后8个迭代执行速度非常快。
编辑:考虑到“assylias”和“Stephen C”的意见,我已更改了代码,链接为http://pastebin.com/Vzb8hGdc,在那里我获得了略微不同的结果:http://pastebin.com/wxiDdRix 。