简体   繁体   中英

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.

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.

Well, there's no need for the "backward" comparison (mostly a holdover from C where a typo could go undetected, if you were using a poor compiler or ignored warnings) - and the conditional operator makes things simpler:

return mServerDevice != null ? mServerDevice.getName() : null;

Or:

    return mServerDevice == null ? null : mServerDevice.getName();

This is both more readable and more efficient than catching NullPointerException .

In more complicated scenarios, just use the if version. You should never be catching NullPointerException unless you're calling into a buggy library which throws it in a way you can't avoid. Exceptions are not meant to be used in this kind of way. They're used to detect programming errors and exceptional external conditions (such as IO failure).

Exceptions are relatively expensive compared with other control flow constructs. However, don't take this too far in the other direction: some people avoid exceptions even when they should be using them, due to a misguided desire to avoid their cost. When used appropriately , exceptions shouldn't be a significant part of your performance profile: if you find they're taking a lot of your time, then either something is badly wrong in your environment (eg you're perpetually trying to connect to a database which you don't have access to) or you're abusing exceptions.

I definitely agree with the rest of answers. To not saying the same exactly, I will only tell you, that now I'm introducing to a quite big commercial source code which has been written for about 3 years and I have not seen any statement using the try-catch approach you have mentioned of; although there were lot of to check for null ;)

Using try-catch clause definitely not a better way.

Also try-catch results in instantiating of new object (the exception). And also if else improves the readability. Thus I'd say that (n!=null) is faster in case you have a lot of cases where n == null. Also n!=null is superfast construct.

Use if-else for situations where you can. Throwing and catching exceptions can be expensive and should be used to handle error cases (not for logical branching).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM