These sentences are equal:
myString != nullmyString.length() > 0! myString.equals("")
Which is the most efficient? (Java 1.4)
These sentences are equal:
myString != nullmyString.length() > 0! myString.equals("")Which is the most efficient? (Java 1.4)
Those aren't all equivalent - a null reference is not the same as an empty string.
The null test will likely be the most efficient because all the others at least require first finding out whether or not the reference is null.
The the best way to find out is to measure the performance:
public static void main(String[] args)
{
String myString = "foo";
int a = 0;
for (int i = 0; i < 100000000; ++i)
{
//if (myString != null)
//if (myString.length() > 0)
if (!myString.equals(""))
{
a++;
}
}
System.out.println(a);
}
The results:
myString != null : 0.61s
myString.length() > 0 : 0.67s
!myString.equals("") : 2.82s
So a null test and a length test take almost the same amount of time, but testing for equality with an empty string takes more than four times longer. Note that I tested on a slightly newer version of Java than you are using, so you should run the tests yourself to see if you get the same results.