Tuesday, January 6, 2015

Performance Improvements StringBuilder and ArrayList and HashMap

Use StringBuilder if Synchronization is not required.

I have used StringBuffer when performing concatenations on string and is far better than using Immutable Strings in Java but if you don't need the synchronization, which most likely could be the case so use StringBuilder

Quote from StringBuilder API:
This class [StringBuilder] provides an API compatible with StringBuffer, but with no guarantee of synchronization. This class is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread (as is generally the case). Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.

Using ArrayList vs LinkedList

LinkedList is great when you don't know the size of the list as it helps.

The default initial capacity of an ArrayList is pretty small (10 from Java 1.4 - 1.7).
But since the underlying implementation is an array, the array must be re-sized if you add a lot of elements.
To avoid the high cost of resizing when you know you're going to add a lot of elements, construct the ArrayList with a higher initial capacity. What's important is to initialize the list when you know upfront the size of the ArrayList and if it is going to be more than 10

List catalogDataVOList = new ArrayList<CatalogDataVO>((int) resultCount);

Reference: http://stackoverflow.com/questions/322715/when-to-use-linkedlist-over-arraylist

Use HashMap vs Hashtable:
If Synchronization is not required use HashMap, Hashtable is a syncrhonized version and typically non synchronized objects perform better.

1 comment:

  1. I have read your blog its very attractive and impressive. I like it your blog.

    Java Training in Chennai Core Java Training in Chennai Core Java Training in Chennai

    Java Online Training Java Online Training JavaEE Training in Chennai Java EE Training in Chennai

    ReplyDelete