dimanche 21 octobre 2018

MethodHandle slower than Reflection? [duplicate]

This question already has an answer here:

I have run a simple test.

    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);
    }
}

But it appears the following result.

8493
249473724
121496

Why is MethodHandle much slower than Reflection? Since Javadoc said MethodHandle should be faster, is there a way to fix this?





Aucun commentaire:

Enregistrer un commentaire