Friday, March 12, 2010

Performance Tip : Make Comparators Singleton

In Effective Java 2nd Edition, Joshua Bloch mentions that Comparator objects should be always Singleton in order to avoid unnecessary Object creation (Item 21, Use functions objects to represent strategies). It gave me a thought that not only Comparators should be made singleton, but all function objects.

If the object contains only functions and has no internal state, there is simply no need to have different instances of that. So, this code:

Collections.sort(stringList, new ReverseStringOrder());

should rather be

Collections.sort(stringList, ReverseStringOrder.getInstance());

And ReverseStringOrder must respectively implement Singleton pattern with getInstance method returning the Singleton instance.

No comments:

Post a Comment