Objects.requireNonNull比旧的方式效率低吗?

23 浏览
0 Comments

Objects.requireNonNull比旧的方式效率低吗?

自从JDK 7以来,我一直很高兴地使用它引入的方法来拒绝传递给不能接受它们的方法的null值:

private void someMethod(SomeType pointer, SomeType anotherPointer) {
    Objects.requireNonNull(pointer, "pointer不能为null!");
    Objects.requireNonNull(anotherPointer, "anotherPointer不能为null!");
    // 方法的其余部分
}

我认为这个方法可以产生非常整洁的代码,易于阅读,我正在努力鼓励同事们使用它。但是一个(特别有知识的)同事抵制,并表示旧的方式更高效:

private void someMethod(SomeType pointer, SomeType anotherPointer) {
    if (pointer == null) {
        throw new NullPointerException("pointer不能为null!");
    }
    if (anotherPointer == null) {
        throw new NullPointerException("anotherPointer不能为null!");
    }
    // 方法的其余部分
}

他说调用requireNonNull涉及将另一个方法放在JVM调用堆栈上,将导致比简单的== null检查更差的性能。

所以我的问题是:是否有任何关于使用Objects.requireNonNull方法会产生性能损失的证据

0