Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Which of the following three functions is more efficient;

  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;
        }
    }

Please reply with concrete acceptable logic.

like image 482
Shridutt Kothari Avatar asked Mar 02 '13 08:03

Shridutt Kothari


People also ask

Which is faster try-catch or if else?

If you've one if/else block instead of one try/catch block, and if an exceptions throws in the try/catch block, then the if/else block is faster (if/else block: around 0.0012 milliseconds, try/catch block: around 0.6664 milliseconds). If no exception is thrown with a try/catch block, then a try/catch block is faster.

Why NullPointerException should not be caught?

It is generally a bad practice to catch NullPointerException. Programmers typically catch NullPointerException under three circumstances: The program contains a null pointer dereference. Catching the resulting exception was easier than fixing the underlying problem.

In which case the NullPointerException will be thrown?

Class NullPointerException Thrown when an application attempts to use null in a case where an object is required. These include: Calling the instance method of a null object. Accessing or modifying the field of a null object.

How do I avoid NullPointerException?

How to avoid the NullPointerException? To avoid the NullPointerException, we must ensure that all the objects are initialized properly, before you use them. When we declare a reference variable, we must verify that object is not null, before we request a method or a field from the objects.


1 Answers

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.

like image 82
Mikhail Vladimirov Avatar answered Sep 23 '22 00:09

Mikhail Vladimirov