0

我有两个使用 JMH 的性能测试。代码很简单,一个是使用Java Reflection,一个是使用MethodHandle(JDK1.7中引入),顺便说一下,isEmptyMethod和MH_isEmpty被声明为static final,像这样:

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 反射:

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

` 方法句柄:

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

下图是性能结果: 性能结果

根据JDK文档。为什么 MethodHandle 不比 java 反射快?上面的代码有什么问题?

4

0 回答 0