Friday, November 21, 2014

Empty String Check

Most of the time we prefer equals method to check whether string is empty or not like in the below method we are checking string with equals method which is returning true or false depending on the String input.



But is it the optimized way to check string?

And the answer is no there is one more way to check whether string is empty or not like in below method we are checking length of string which will perform much better than equals method.




Here is the sample program :-

public class EmptyString {

            public static void main(String[] args) {
                        long startTime = System.currentTimeMillis();
                        for (long i = 0; i < 8300000; i++) {
                                    isEmptyEquals("");
                        }
                        long endTime = System.currentTimeMillis();

                        System.out.println("Time taken by equals check method(in milliseconds) : " + (endTime - startTime) + "ms");

                        startTime = System.currentTimeMillis();
                        for (long i = 0; i < 8300000; i++) {
                                    isEmptyLength("");
                        }
                        endTime = System.currentTimeMillis();
                        System.out.println("Time taken by length check method(in milliseconds) : " + (endTime - startTime) + "ms");
            }

            public static boolean isEmptyEquals(String str) {
                        return str == null || str.equals("");
            }

            public static boolean isEmptyLength(String str) {
                        return str == null || str.length() == 0;
            }

}

And the output of the above program is (on my machine)

Time taken by equals check method(in milliseconds) : 119ms
Time taken by length check method(in milliseconds) : 35ms


In Java 6 isEmpty method is added in String class which checks length to verify that String is empty or not. Therefore if we are working on java version 6 or greater than 6 then we can use isEmpty method of String class.
Snapshot taken from String class




No comments:

Post a Comment