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




Iterator vs get(index) method

Iterator vs get(index) method

We can traverse list using for loop or an Iterator. Sometimes iterator perform traversing faster than for loop for example, linked list is a classic example, Linked list class has get(index) method but it is slow because linked list is a sequential data structure and here is the implementation of get(index) method (taken from  java.util.LinkedList class)





As we can see to get the element at particular index java needs to put some effort, it has to reach up to that index to get the element at that particular index




If list is accessed frequently then you will see the difference in performance while using get(index) method of linked list as compared to traversing list using iterator.

Let’s take a look at the following example:-

public class Performance {
                public static void main(String[] args) {
                                int count = 100000;
                                LinkedList<Integer> linkedLst = new LinkedList<Integer>();
                                ArrayList<Integer> arrayLst = new ArrayList<Integer>();
                                for (int i = 0; i != count; i++) {
                                                int x = (int) Math.random();
                                                linkedLst.add(x);
                                                arrayLst.add(x);
                                }
                                long t = System.currentTimeMillis();
                                for (int i = 0; i != count; i++) {
                                                linkedLst.get(i);
                                }
                                t = System.currentTimeMillis() - t;
                                System.out.println("Time taken by Linked List get(index) " + t + "(ms)");

                                t = System.currentTimeMillis();
                                for (Iterator<Integer> itr = linkedLst.iterator(); itr.hasNext();) {
                                                itr.next();
                                }
                                t = System.currentTimeMillis() - t;
                                System.out.println("Time taken by Linked List Iterator " + t + "(ms)");

                                t = System.currentTimeMillis();
                                for (int i = 0; i != count; i++) {
                                                arrayLst.get(i);
                                }
                                t = System.currentTimeMillis() - t;
                                System.out.println("Time taken by Array List get(index) " + t + "(ms)");

                                t = System.currentTimeMillis();
                                for (Iterator<Integer> itr = arrayLst.iterator(); itr.hasNext();) {
                                                itr.next();
                                }
                                t = System.currentTimeMillis() - t;
                                System.out.println("Time taken by Array List Iterator " + t + "(ms)");

                }
}

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

Time taken by Linked List get(index) 3412(ms)
Time taken by Linked List Iterator 9(ms)
Time taken by Array List get(index) 3(ms)
Time taken by Array List Iterator 7(ms)

You can see the difference in performance therefore if you want to traverse list then choose option wisely J.

And in many cases you don’t know whether you want a linked list or an array list or some other list implementation in that case using iterator to traverse a list is a more reliable choice because iterator gives fairly good performance in case of array list (although not fastest) and in case of traversing linked list it gives much comparable results then for loop and it protects from the extremely slow performance you would get if you mistakenly used a get(index) on a linked list.