These sentences are equal:
myString != nullmyString.length() > 0! myString.equals("")
Which is the most efficient? (Java 1.4)
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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:
The results:
myString != null : 0.61s myString.length() > 0 : 0.67s !myString.equals("") : 2.82sSo 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.