在《effective java》中‘避免创建不必要的对象’一节,有如下代码
private static long sum() {
Long sum = 0L;
for (long i = 0; i <= Integer.MAX_VALUE; i++)
sum += i;
return sum; }
This program gets the right answer, but it is much slower than it should be, due to a one-character typographical error. The variable sum is declared as a Long instead of a long, which means that the program constructs about 231 unnecessary Long instances (roughly one for each time the long i is added to the Long sum).
为什么把sum设置成Long对象,会在每一次循环的时候创建Long实例?
0,不知道这本书的 序言 你看了没有,若你看了就应该知道它不适合初学者,否则你也不会有这样的问题了
1,对于你所提的问题,像这样直接给包装类型赋值,jvm在执行时相当于调用该包装类的valueof方法,对于Long的valueof方法java.lang.Long#valueOf(long),如果i不在long cache 中,那么就new Long(i) 一个新对象,显然上述代码中,在sum几次遍历后大于127就会创建新的实例,至于为什么有long cache,你可以理解为帮机器节省内存(毕竟这些类上世纪就已经设计出来了,那时的机器内存可没有现在这么多)