有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为什么方法访问看起来比字段访问快?

我做了一些测试来找出使用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次迭代执行得非常快


Edit:在考虑了assyliasStephen C注释后,我将代码更改为http://pastebin.com/Vzb8hGdc,得到了稍微不同的结果:http://pastebin.com/wxiDdRix


共 (1) 个答案

  1. # 1 楼答案

    原因是你的基准被打破了

    第一次迭代使用解释器完成

    Field Access:  1528500478 ns
    Method Access: 1521365905 ns
    

    第二次迭代首先由解释器完成,然后我们转而运行JIT编译的代码

    Field Access:  1550385619 ns
    Method Access: 47761359 ns
    

    其余的迭代都是使用JIT编译代码完成的

    Field Access:  68 ns
    Method Access: 33 ns
    
    etcetera
    

    它们速度快得难以置信的原因是JIT编译器对循环进行了优化。它检测到它们对计算没有贡献任何有用的东西。(不清楚为什么第一个数字似乎始终比第二个数字快,但我怀疑优化后的代码是否以任何有意义的方式衡量了字段访问和方法访问。)


    更新后的代码/结果:很明显,JIT编译器仍在优化循环