Effective Java 05 Avoid creating unnecessary objects
2014-02-27 19:31 小郝(Kaibo Hao) 阅读(369) 评论(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
- 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.
- Prefer primitives to boxed primitives, and watch out for unintentional autoboxing.
出处:http://www.cnblogs.com/haokaibo/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。