0

These sentences are equal:

  • myString != null
  • myString.length() > 0
  • ! myString.equals("")

Which is the most efficient? (Java 1.4)

2
  • 6
    It doesn't matter. Move on to something important. Commented Jul 30, 2010 at 22:58
  • 4
    @JohnFx: something important like, say, the meaning of life? Anyway, what IS important is that unlike stated in the questions, these are NOT EQUAL AT ALL. Commented Jul 30, 2010 at 23:07

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

Comments

1

They are not equivalent. If myString is null the 2nd one will throw a NullPointerException.

That said, (myString != null && myString.length() != 0) might be slightly more efficient than ("".equals(myString)). But they'll still react differently to myString being null.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.