0

我已经运行了一个简单的测试。

    public static void main (String[] args) throws java.lang.Throwable
    {
        //Field field = Unsafe.class.getDeclaredField("theUnsafe");
        //field.setAccessible(true);
        //Unsafe unsafe = (Unsafe) field.get(null);
        long start1 = System.nanoTime();
        new Main();
        System.out.println(System.nanoTime() - start1);
        //long start2 = System.nanoTime();
        //unsafe.allocateInstance(Main.class);
        //System.out.println(System.nanoTime() - start2);
        long start3 = System.nanoTime();
        MethodHandles.publicLookup().findConstructor(Main.class, MethodType.methodType(void.class)).invoke();
        System.out.println(System.nanoTime() - start3);
        long start4 = System.nanoTime();
        Main.class.getConstructor().newInstance();
        System.out.println(System.nanoTime() - start4);
    }
}

但它出现了以下结果。

8493
249473724
121496

为什么 MethodHandle 比 Reflection 慢得多?由于 Javadoc 说 MethodHandle 应该更快,有没有办法解决这个问题?

4

0 回答 0