Item 5: Avoid creating unnecessary objects

- Gaurav
Don't be shellfish...Google+FacebookTwitterLinkedInRedditDiggtumblrPinterest

Avoid creating unnecessary objects

This post will be bulleted as it shares more than one instance to take care of.

new String(“SomeString”)

This is a crime, the reason being Strings in java are immutable objects. “SomeString” string is an object itself, and new String(“”) creates another object.

So, String s = “SomeString”; is suffice

Go for static factory methods

e.g. when creating a boolean, try using Boolean.valueOf(String) instead of Boolean(String). Boolean(String) creates a new object each time. Boolean.TRUE, Boolean.False is also a very good option.

Read more for two mindblowing examples

Unnecessary Object Creation

The example shows a DateUtil class with a helper method boolean is90sDate(Date dateValue). This method returns true only if the given date is a date from the 90s.

/**
 * Unnecessary object creation example
 */
public class DateUtil {

   /*
    * Returns true only if the date is of the 90s decade
    *
    * @param dateValue
    * @return
    */
   public static boolean is90sDate(
      Date dateValue) {
         Date startDate;
         Date endDate;
         Calendar calendar = Calendar.getInstance();
         calendar.set(1991, Calendar.JANUARY, 1,
               0, 0, 0);
         startDate = calendar.getTime();
         calendar.set(2000, Calendar.DECEMBER, 31,
               23, 59, 59);
         endDate = calendar.getTime();
         return (dateValue.compareTo(startDate) >= 0
               && dateValue.compareTo(endDate)
   }
}

Each method invocation get a calendar instance, which is used to create two new dates. These dates are supposed to be created every time the invocation is done. This might slow you down a little. Instead, the two instances can be made once at the class load, by placing their initiation in a static block.

/**
 * The right way of doing it example
 */
public class DateUtil {

	private static Date startDateOf90s;
	private static Date endDateOf90s;

	// Initialize the start and end date of, on class load
	static {
		Calendar calendar = Calendar.getInstance();
		calendar.set(1991, Calendar.JANUARY, 1,
				0, 0, 0);
		startDateOf90s = calendar.getTime();
		calendar.set(2000, Calendar.DECEMBER, 31,
				23, 59, 59);
		endDateOf90s = calendar.getTime();
	}

	/*
	 * Returns true only if the date is of the 90s decade
	 * 
	 * @param dateValue
	 * @return
	 */
	public static boolean is90sDate(
			Date dateValue) {
		return (dateValue.compareTo(startDateOf90s) >= 0
		&& dateValue.compareTo(endDateOf90s) 
        }
}

Handling Autoboxing with care

Java 1.5 introduced the autoboxing. Which now made it possible for a developer not to care about mixing the primitives with their wrapper classes. But, wait for a second. How does the magic happen? Well, whenever you do a,
Long var = 2l;

2l first gets converter to a Long object and then is assigned to the variable var. This is most can be avoided as var easily could have been primitive long. Have a look at this example from effective java.

// Hideously slow program! Can you spot the object creation?
public static void main(String[] args) {
   Long sum = 0L;
   for (long i = 0; i < Integer.MAX_VALUE; i++) {
      sum += i;
   }
   System.out.println(sum);
}

I’m sure you’ve spotted the culprit. ;-)

Don't be shellfish...Google+FacebookTwitterLinkedInRedditDiggtumblrPinterest