For the following conditionals:
if (a != null && a instanceof A)
or
if (a instanceof A)
Is there any advantage (for example, performance-wise) to check for null
first? Both conditionals should be equal in result.
For the following conditionals:
if (a != null && a instanceof A)
or
if (a instanceof A)
Is there any advantage (for example, performance-wise) to check for null
first? Both conditionals should be equal in result.
No advantage whatsoever, you can just do with
if(a instanceof A) {}
this will return evaluate to false if a is null
The JVM has to check for null itself. Not much point in doing it twice.
if(a instanceof A)
is enough.
The if(a!=null && expr)
pattern is used when expr
will throw a NullPointerException
if a
is null. a instanceof A
doesn't throw a NPE and just returns false
if a
is null.
The instanceOf operator does not need explicit null checks, as it does not throw a null pointer exception if the operand is null.
At run time, the result of the instanceOf operator is true if the value of the relational expression is not null and the reference could be cast to the reference type without raising a class cast exception.
If the operand is null, the instanceOf operator returns false and hence, explicit null checks are not required.
Consider the below example,
public static void main(String[] args) {
if(a != null && a instanceof ArrayList){ //Violation
System.out.println("In if block");
}
else
{
System.out.println("In else block");
}
}
The correct usage of instanceOf is as shown below,
public static void main(String[] args) {
if(a instanceof ArrayList){ //Correct way
System.out.println("In if block");
}
else
{
System.out.println("In else block");
}
}
I seriously doubt that that there is any benefit to checking for null first. It is up to how the VM implements the instancof check... odds are it does the if itself as the first part of the code.