if(null check)-else vs try catch(NullPointerException)哪个更有效?

shr*_*ari 16 java performance performance-testing

以下哪三个功能更有效;

  public String getmConnectedDeviceName1() {
        if(null != mServerDevice) {
            return mServerDevice.getName();
        }
        else {
            return null;
        }
    }

  public String getmConnectedDeviceName2() {
        return mServerDevice == null ? null : mServerDevice.getName();
    }


  public String getmConnectedDeviceName3() {
        try{
            return mServerDevice.getName();
        }
        catch(NullPointerException e) {
            return null;
        }
    }
Run Code Online (Sandbox Code Playgroud)

请回复具体可接受的逻辑.

Mik*_*rov 28

前者是更有效时,mServerDevicenull.什么时候mServerDevice不是null两者都差不多.比较null只是比较两个32位整数,这是非常快的操作.抛出异常是很昂贵的,因为应该创建新对象并且应该填充堆栈跟踪.

Trenary运算符... ? ... : ...if (...) ... else ...语句完全一样有效,因为它们都被转换为相同的字节码.


Jon*_*eet 19

好吧,没有必要进行"向后"比较(主要是从C中保留,如果您使用的是错误的编译器或忽略警告,可能无法检测到拼写错误) - 并且条件运算符使事情变得更简单:

return mServerDevice != null ? mServerDevice.getName() : null;
Run Code Online (Sandbox Code Playgroud)

要么:

    return mServerDevice == null ? null : mServerDevice.getName();
Run Code Online (Sandbox Code Playgroud)

这比捕获更具可读性效率NullPointerException.

在更复杂的场景中,只需使用该if版本.你永远不应该捕捉,NullPointerException除非你正在调用一个无法避免的错误库.例外并不意味着以这种方式使用.它们用于检测编程错误和异常外部条件(例如IO故障).

与其他控制流构造相比,例外相对昂贵.但是,不要在另一个方向上走太远:有些人甚至在他们应该使用它们时避免例外,因为他们错误地避免了他们的成本.如果使用得当,异常不应该是您的性能配置文件的重要部分:如果您发现它们占用了大量时间,那么您的环境中的任何一个都是严重错误的(例如,您不断尝试连接到您无权访问的数据库)或您滥用异常.

  • @shriduttkothari:"这比捕获NullPointerException更可读,更有效"的哪一部分没有说哪个更有效?请注意,您应该*非常*很少以牺牲可读性为代价进行微优化 - 当您这样做时,您应该已经进行了测试,以便您可以轻松地告诉自己. (4认同)