Item 05 - Avoid creating unnecessary objects

From Effective Java 2/e by Joshua Bloch

Case of String

// Creating two String objects
String s = new String("Hello World");

// Creating one String object
String s = "Hello World";

Case of static factory methods

// Creating Boolean object
Boolean b = Boolean("false");

// Reusing Boolean object
Boolean b = Boolean.valueOf("true");

Use case of static initializer

public class Person {
   private final Date birthDate;
   // Other fields, methods, and constructor omitted

   // DON'T DO THIS!
   public boolean isBabyBoomer() {
      // Unnecessary allocation of expensive object
      Calendar gmtCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
      gmtCal.set(1946, Calendar.JANUARY, 1, 0, 0, 0);

      Date boomStart = gmtCal.getTime();
      gmtCal.set(1965, Calendar.JANUARY, 1, 0, 0, 0);

      Date boomEnd = gmtCal.getTime();
      return birthDate.compareTo(boomStart) >= 0 && birthDate.compareTo(boomEnd) < 0;
   }
}
class Person {
   private final Date birthDate;
   // Other fields, methods, and constructor omitted
   /**
    * The starting and ending dates of the baby boom.
    */
   private static final Date BOOM_START;
   private static final Date BOOM_END;
   static {
      Calendar gmtCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
      gmtCal.set(1946, Calendar.JANUARY, 1, 0, 0, 0);
      BOOM_START = gmtCal.getTime();

      gmtCal.set(1965, Calendar.JANUARY, 1, 0, 0, 0);
      BOOM_END = gmtCal.getTime();
   }

   public boolean isBabyBoomer() {
      return birthDate.compareTo(BOOM_START) >= 0 && birthDate.compareTo(BOOM_END) < 0;
   }
}

Times to run isBabyBoomer 100,000 times * Old Example : 32000ms * New Example : 130ms

User primitives instead of auto-boxed-primitives and watch out unintentional auto-boxing

// Takes 43 seconds
public static void main(String... args) {
   Long sum = 0L;
   for (long i = 0; i < Integer.MAX_VALUE; i++) {
      sum += i;
   }
   System.out.println(sum);
}

// Takes 6.8 seconds
public static void main(String... args) {
   long sum = 0L;
   for (long i = 0; i < Integer.MAX_VALUE; i++) {
      sum += i;
   }
   System.out.println(sum);
}

Don’t create a new object when you should reuse an existing one

Posted by The Finest Artist