代码改变世界

Effective Java 05 Avoid creating unnecessary objects

2014-02-27 19:31  小郝(Kaibo Hao)  阅读(366)  评论(0编辑  收藏  举报

String s = new String("stringette"); // Don't do this. This will create an object each time

Vs

String s = "stringette";

 

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;

}

}

   

NOTE

  1. When using Adapter pattern don't created an new object of the backing object since there is no need for the specific state of the Adapter object.
  2. Prefer primitives to boxed primitives, and watch out for unintentional autoboxing.