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.
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.
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.
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 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With