就像我们大部分人所知道的,最好能重用对象,而不是每次都重复创建一个功能相同的新对象,下面举几个例子说明这个点。
重用不可变对象
如果对象是不可变的,那么它就始终可以被重用。对于同时提供了静态工厂方法和构造方法的不可变类,通常使用静态工厂方法而不是构造方法,以避免创建不必要的对象,尽管同时提供两种方法的场景不太多。例如静态工厂方法Boolean.valueOf(String)
几乎总是优于构造方法Boolean(String)
,从源码注释中我们也能看到相应的提示信息。
/**
* Allocates a {@code Boolean} object representing the
* {@code value} argument.
*
* <p><b>Note: It is rarely appropriate to use this constructor.
* Unless a <i>new</i> instance is required, the static factory
* {@link #valueOf(boolean)} is generally a better choice. It is
* likely to yield significantly better space and time performance.</b>
*
* @param value the value of the {@code Boolean}.
*/
public Boolean(boolean value) {
this.value = value;
}
/**
* Returns a {@code Boolean} instance representing the specified
* {@code boolean} value. If the specified {@code boolean} value
* is {@code true}, this method returns {@code Boolean.TRUE};
* if it is {@code false}, this method returns {@code Boolean.FALSE}.
* If a new {@code Boolean} instance is not required, this method
* should generally be used in preference to the constructor
* {@link #Boolean(boolean)}, as this method is likely to yield
* significantly better space and time performance.
*
* @param b a boolean value.
* @return a {@code Boolean} instance representing {@code b}.
* @since 1.4
*/
public static Boolean valueOf(boolean b) {
return (b ? TRUE : FALSE);
}
重用已知不会修改的可变对象
先看一段示例代码:
public class Item5 {
public long getFoundedTimeMillisFromNow() {
Calendar calendar = Calendar.getInstance();
calendar.set(1978, Calendar.NOVEMBER, 10, 0, 0, 0);
return System.currentTimeMillis() - calendar.getTime().getTime();
}
}
上面的代码计算七天后的时间,getFoundedTimeMillis()都会获取Calendar的一个实例,此处Calendar非单例,如果多次调用则产生了多个Calendar实例,在我电脑上测试调用1000万次耗时3843ms,如果我们对它进行简单修改:
public class Item5 {
private static long birthTimeMillis;
static {
Calendar calendar = Calendar.getInstance();
calendar.set(1978, Calendar.NOVEMBER, 10, 0, 0, 0);
birthTimeMillis = calendar.getTime().getTime();
}
public long getFoundedTimeMillisFromNow() {
return System.currentTimeMillis() - birthTimeMillis;
}
}
单独提出用于对比的基准时间birthTimeMillis,类加载时通过一个Calendar获取它的值,之后它不会再变化,修改后测试调用1000万次耗时414ms。
注意自动装箱问题
自Java 1.5开始引入了自动装箱(autobox),使得基本类型与装箱基本类型之间的差别变的模糊起来,如果不注意他们在语意上的差别则可能产生性能上的差异。
Long sum = 0L;
long startTime = System.currentTimeMillis();
for (long i = 0; i <= Integer.MAX_VALUE; i++) {
sum += i;
}
上面这段代码计算所有正整数的和,经测试,耗时7838ms。现在我们对其进行修改:
long sum = 0L;
long startTime = System.currentTimeMillis();
for (long i = 0; i <= Integer.MAX_VALUE; i++) {
sum += i;
}
重新对其测试,耗时758ms,从测试结果上我们可以看到两者间明显的差距,这是因为第一段代码将sum
定义成了Long
类型,导致每累加一次便会实例化一个Long对象。从这里,可以看到结论很明显,要优先使用基本类型二不是装箱基本类型,要注意这种自动装箱的问题。