Why are interface method invocations slower than concrete invocations?

后端 未结 6 932
伪装坚强ぢ
伪装坚强ぢ 2020-11-27 15:24

This is question comes in mind when I finding difference between abstract class and interface. In this post I came to know that interfaces are slow as they required extra in

6条回答
  •  醉梦人生
    2020-11-27 16:03

    This is variation on Bozho example. It runs longer and re-uses the same objects so the cache size doesn't matter so much. I also use an array so there is no overhead from the iterator.

    public static void main(String[] args) {
        Random random = new Random();
        int testLength = 200 * 1000 * 1000;
        Foo[] foos = new Foo[testLength];
        Bar[] bars = new Bar[testLength];
        Foo1Impl foo1 = new Foo1Impl();
        Foo2Impl foo2 = new Foo2Impl();
        Bar1Impl bar1 = new Bar1Impl();
        Bar2Impl bar2 = new Bar2Impl();
        for (int i = 0; i < testLength; i++) {
            boolean flip = random.nextBoolean();
            foos[i] = flip ? foo1 : foo2;
            bars[i] = flip ? bar1 : bar2;
        }
        long start;
        start = System.nanoTime();
        for (Foo foo : foos) {
            foo.foo();
        }
        System.out.printf("The average abstract method call was %.1f ns%n", (double) (System.nanoTime() - start) / testLength);
        start = System.nanoTime();
        for (Bar bar : bars) {
            bar.bar();
        }
        System.out.printf("The average interface method call was %.1f ns%n", (double) (System.nanoTime() - start) / testLength);
    }
    

    prints

    The average abstract method call was 4.2 ns
    The average interface method call was 4.1 ns
    

    if you swap the order the tests are run you get

    The average interface method call was 4.2 ns
    The average abstract method call was 4.1 ns
    

    There is more difference in how you run the test than which one you chose.

    I got the same result with Java 6 update 26 and OpenJDK 7.


    BTW: If you add a loop which only call the same object each time, you get

    The direct method call was 2.2 ns
    

提交回复
热议问题