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

后端 未结 6 1733
春和景丽
春和景丽 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 17:56

    The former is much more efficient when mServerDevice is null. When mServerDevice is not null both are about the same. Comparison with null is just comparison of two 32-bit integers which is very fast operation. Throwing an exception is expensive, because new objects ought to be created and stack trace ought to be filled.

    Trenary operator ... ? ... : ... is exactly as efficient as if (...) ... else ... statement, because both are translated to the same bytecode.

提交回复
热议问题