如果一个对象是非可变的,那么它在程序中上可以被重用的,如:
//不推荐,"test"本来就是一个String实例,如果此方法在一个循环中或者被频繁的调用,将会严重影响性能
String s = new String("test");
//推荐方式
String s = "test";
对于提供静态方法和构造函数的非可变类,推荐使用静态方法,这样可以避免重复创建对象,如:
Boolean.vauleOf(String)方法优于构造函数Boolean(String)
如下Person类在每次调用isBabyBoomer()方法时都需新创建对象,极大的影响了性能。
import java.util.*;
public class Person {
private final Date birthDate;
public Person(Date birthDate) {
// Defensive copy - see Item 39
this.birthDate = new Date(birthDate.getTime());
}
// Other fields, methods 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;
}
}
改进方案如下:
import java.util.*;
class Person {
private final Date birthDate;
public Person(Date birthDate) {
// Defensive copy - see Item 39
this.birthDate = new Date(birthDate.getTime());
}
// Other fields, methods
/**
* 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;
}
}
这样类变量在类在初始化创建Calendar、Date、TimeZone时只需创建一次,已经初始化的不再进行初始化操作,性能好于前一种方法一百倍。【static变量在系统没有调用isBabyBoomer() 方法之前,不会进行初始化(延迟初始化)】
类初始化的顺序:先初始化父类的静态代码--->初始化子类的静态代码-->初始化父类的非静态代码--->初始化父类构造函数--->初始化子类非静态代码--->初始化子类构造函数。