0

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?

Bernard
  • 304
  • 2
  • 11
  • 2
    Your benchmark is suspect. Please read up on the problems of writing valid Java micro-benchmarks (https://stackoverflow.com/questions/504103/how-do-i-write-a-correct-micro-benchmark-in-java), and do the benchmarking using `jmh`, `calliper` ... or similar. Once you have done that, we can talk about what the results mean. – Stephen C Oct 21 '18 at 23:44
  • 1
    What is benchmark? How is it related? – Bernard Oct 22 '18 at 02:15
  • 2
    Your "simple test" is a benchmark. The point is that you claim that your "simple test" is saying that method handles are slower than reflection. In fact, because of the flaws in the way you are measuring, the performance numbers are suspect, and don't actually provide reliable evidence of anything. – Stephen C Oct 22 '18 at 03:09
  • @StephenC to be fair, they give an indication of how long it took the first time for this run. Another run with slightly different code however .... – Peter Lawrey Oct 22 '18 at 07:38
  • Well yes. But the time taken "the first time" is likely to be very uncharacteristic of the steady state behavior. And look at the time taken (supposedly). 249 **milliseconds**. – Stephen C Oct 22 '18 at 09:01
  • I tried warming up jvm then do the test. Method handle is still slower than reflection. – Bernard Oct 22 '18 at 10:29
  • 1
    Letting the flaws of your “benchmark” aside, the focus of method handles lies on the *invocation* performance, not the lookup. When you measure the costs of repeated invocations of an already acquired method handle, you will get an entirely different picture. – Holger Oct 23 '18 at 16:48

0 Answers0