作者:Breerus | 来源:互联网 | 2024-10-28 14:18
在《effective java》中‘避免创建不必要的对象’一节,有如下代码12345private static long sum() { Long sum = 0L; fo
在《effective java》中‘避免创建不必要的对象’一节,有如下代码
1 2 3 4 5
| 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实例?