Reputation: 2031
What is better use in order to check if object is null.
To check if the object is null or to set a flag for it. By saying better im looking for performance (faster and safer).
public class A
{
Object test;
boolean isTestObjectSet;
public A(Object test)
{
this.test = test;
isTestObjectSet = true;
}
public A()
{
}
public void doSomething()
{
if(test != null)
//do something
//VS
if(isTestObjectSet)
//do something
}
}
Upvotes: 0
Views: 68
Reputation: 129517
Using isTestObjectSet
is just making things more complicated than they need to be. Just use test != null
: it better conveys your intention and doesn't force you to keep this isTestObjectSet
variable in-sync with whether or not test
is set. There is absolutely no performance difference between the two variants.
Upvotes: 3
Reputation: 116
In my opinion - explicit checks (comparing to 'null') is faster, in terms not cluttering your code with many intermediary boolean variables. Safer? Both of the checks are boolean checks, so it is always 'true'/'false' comparison.
Upvotes: 2