jeudi 23 juillet 2020

Why MethodHandle is slow than Reflection in JDK 1.8?

I have two performance tests using JMH. The code is very easy,one is using Java Reflection,Another is using MethodHandle(Introduced in JDK1.7),By The way,isEmptyMethod and MH_isEmpty is declared as static final,like this:

private static final MethodHandle MH_isEmpty;
private static final Method isEmptyMethod;

static {
    try {
        MH_isEmpty = MethodHandles.publicLookup().findVirtual(String.class, "isEmpty", MethodType.methodType(boolean.class));
        isEmptyMethod = String.class.getDeclaredMethod("isEmpty");
    } catch (Exception ex) {
        throw new UnsupportedOperationException();
    }
}

` Java Reflection:

@BenchmarkMode(Mode.Throughput)
public void testReflectionGetIsEmpty() throws Exception {
    isEmptyMethod.setAccessible(false);
    final Object result = isEmptyMethod.invoke("SmartLee");
}

` MethodHandle:

@Benchmark
@BenchmarkMode(Mode.Throughput)
public void testFindVirtual() throws Throwable {
    final MethodHandle isEmpty = MH_isEmpty.bindTo("SmartLee");
    isEmpty.invoke();
}

Beblow is the performance results: performance results

According to JDK docs.Why MethodHandle is not faster than java reflection? What's wrong with above code?





Aucun commentaire:

Enregistrer un commentaire