Sunday, June 29, 2014

Optimize way to check empty String in Java

In this post, we'll see the best practice and optimize way to check empty String in Java. Every developer know how to check empty String but here we'll look into the optimized method of checking empty String. 

Most of us always prefer to use equals() method to check for empty String such as



However, this equals() method is overkill to test for an empty String. It is quicker to test if the length of the String is 0. So, the best way to check for empty String is 



How to prove that second option is the optimized way to check for empty String? 
For this, I have done micro-tuning. Micro-tuning should always start with a baseline measurement. The most basic tool in the tuner's armory is the System.currentTimeMillis() method, which returns the current time in milliseconds, as a long data item. This method returns the time offset from some starting time, but we don't actually care what that starting time is because we will use the currentTimeMillis() method to measure a time difference, the elapsed time between the start and end of our test



5 test result : 
Test run 1
Time in Mili Sec to length : 60
Time in Mili Sec to equals : 120
Test run 2
Time in Mili Sec to length : 53
Time in Mili Sec to equals : 98
Test run 3
Time in Mili Sec to length : 62
Time in Mili Sec to equals : 101
Test run 4
Time in Mili Sec to length : 54
Time in Mili Sec to equals : 89
Test run 5
Time in Mili Sec to length : 65
Time in Mili Sec to equals : 118

String.equals() is expensive if you are only testing for an empty string. It is quicker to test if the length of the string is 0.
Reason is that, since String class is immutable so there length is cached where in case of equals() a lot of statements need to be executed to know whether string is empty or not.
Onward Java 6, isEmpty() method of String is use for the same purpose.

What about if String is NULL?
In this case, you can add one condition of null check before checking length of the String. For instance,


Download CodeEmptyString EmptyStringWithNull



If you know anyone who has started learning Java, why not help them out! Just share this post with them. Thanks for studying today!...

17 comments:

  1. The best way to check if a String is empty is str.isEmpty().

    ReplyDelete
  2. Thanks for sharing excellent post on java. Can you share some of the reputed training institutes offering professional training and placement assistance? “”
    JAVA J2EE Training in Chennai

    ReplyDelete
  3. Thanks for valuable info
    But I found error in above example saying str.length()==0 is not possible ,plz refer
    http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java

    ReplyDelete
    Replies
    1. Did you try it yourself? If yes, please share the code.

      Delete
    2. Yeah Pradeep ,I have tried your above example.my code is:

      public class StringLength {

      public static void main(String[] args) {

      long startTime1 = System.currentTimeMillis();

      for(long i=0;i<7200000;i++)
      {
      isEmptyNew("");
      }
      System.out.println("Time Interval Using Equals:" + (System.currentTimeMillis() - startTime1));

      long startTime2 = System.currentTimeMillis();
      for(long j=0;j<7200000;j++)
      {
      isEmpty("");
      }

      System.out.println("Time Interval Using Length:" + (System.currentTimeMillis() - startTime2));

      }//main
      public static boolean isEmpty(String str)
      {
      return str.length() == 0;
      }

      public static boolean isEmptyNew(String str)
      {
      return str.equals("");
      }

      }

      Delete
    3. At str.length()==0
      Errors that compiler reports: invalid assignment operator
      LHS of assignment must be a variable.

      Delete
    4. I didn't find problem anywhere.

      Delete
  4. This information you provided in the blog that was really unique I love it!!, Thanks for sharing such a great blog..Keep posting..

    J2EE Training in Chennai

    ReplyDelete
  5. Thanks for sharing such informative article on Java technology. It is most preferred technology among developers to create stunning mobile application fast and easy. It also created massive career opportunity for aspiring professionals. JAVA Training

    ReplyDelete
  6. Thanks for sharing this valuable information to our vision. You have posted a trust worthy blog keep sharing.JAVA Training in Chennai

    ReplyDelete
  7. It helps the software developers and programmers to validate software application performance and behavior before deployment.Nice article.
    SEO Training in chennai|SEO Training chennai

    ReplyDelete
  8. very nice blogs!!! i have to learning for lot of information for this sites...Sharing for wonderful information.
    Cloud Computing Training in chennai | Cloud Computing Training chennai

    ReplyDelete

  9. Article gives a great information about Java.Now i ready to face any problems in Java. Thanks for giving useful information.
    VMWare Training in chennai | VMWare Training chennai

    ReplyDelete
  10. The information you have given here are most worthy for me. I have implemented in my training program as well, thanks for sharing.

    Hadoop Training Chennai
    Hadoop Training in Chennai

    ReplyDelete
  11. Interesting artickle. You can check your java skills, with such tricky questions on next sites: http://gradestack.com/Java-Programming-Guide/2874/course-page, http://quizful.com/browseQuizes, http://smarterer.com/tests/core-java

    ReplyDelete
  12. The information you have deliver here is really useful to make my knowledge good. Thanks for your heavenly post. It is truly supportive for us and I have accumulated some essential data from this blog.
    Regards,
    Informatica training institute in Chennai|Best Informatica Training Institute In Chennai|Informatica training in chennai

    ReplyDelete
  13. This information is impressive; I am inspired with your post writing style & how continuously you describe this topic. After reading your post, thanks for taking the time to discuss this, I feel happy about it and I love learning more about java.
    Regards,
    ccna course in Chennai|ccna training in Chennai

    ReplyDelete