if(null check)-else vs try catch(NullPointerException) which is more efficient?

后端 未结 6 1745
春和景丽
春和景丽 2020-12-28 17:48

Which of the following three functions is more efficient;

  public String getmConnectedDeviceName1() {
        if(null != mServerDevice) {
            retur         


        
6条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-28 18:18

    Regardless of performance, I would prefer the if-else form. Suppose mServerDevice is not null, but something goes badly wrong during the getName() call and it throws a NullPointerException. The exception-based version will silently return null, without logging the error.

提交回复
热议问题