private static long getcounterresult() {
long sum = 0l;
final int length = integer.max_value;
for (int i = 0; i < length; i++) {
sum += i;
}
return sum;
}
public static void main(string[] args) {
long startcounttime = system.currenttimemillis();
long result = getcounterresult();
long endcounttime = system.currenttimemillis();
system.out.println("result = " + result + ", and take up time : " + (endcounttime - startcounttime) / 1000 + "s");
}
在我的电脑(macos 64位系统,配置较高),打印结果如下:
result = 2305843005992468481, and take up time : 12s
/**
* returns an {@code integer} instance representing the specified
* {@code int} value. if a new {@code integer} instance is not
* required, this method should generally be used in preference to
* the constructor {@link #integer(int)}, as this method is likely
* to yield significantly better space and time performance by
* caching frequently requested values.
*
* this method will always cache values in the range -128 to 127,
* inclusive, and may cache other values outside of this range.
*
* @param i an {@code int} value.
* @return an {@code integer} instance representing {@code i}.
* @since 1.5
*/
public static integer valueof(int i) {
// 如果i的值大于-128小于127则返回一个缓冲区中的一个integer对象
if (i >= integercache.low && i <= integercache.high)
return integercache.cache[i + (-integercache.low)];
// 否则返回 new 一个integer 对象
return new integer(i);
}
public static void main(string[] args) {
// ⓵
integer a = new integer(121);
integer b = new integer(121);
system.out.println(a == b);
// ⓶
integer c = 121;
integer d = 121;
system.out.println(c == d);
// ⓷
integer e = 129;
integer f = 129;
system.out.println(e == f);
// ⓸
int g = 50;
integer h = new integer(50);
system.out.println(g == h);
}
public static long valueof(long l) {
final int offset = 128;
if (l >= -128 && l <= 127) { // will cache
return longcache.cache[(int)l + offset];
}
return new long(l);
}
很明显我们声明了一个 long 的对象 sum,由于自动装箱,这句代码并没有语法上面的错误,编译器当然也不会报错。上面代码等同于如下代码:
long sum = long.valueof(0);
在 for 循环中,超过 [-128,127] 就会创建新的对象,这样不断的创建对象,不停的申请堆内存,程序执行自然也就比较耗时了。
修改一下代码,如下:
private static long getcounterresult() {
// 修改为普通的基本类型数据
long sum = 0l;
final int length = integer.max_value;
for (int i = 0; i < length; i++) {
sum += i;
}
return sum;
}
public static void main(string[] args) {
long startcounttime = system.currenttimemillis();
long result = getcounterresult();
long endcounttime = system.currenttimemillis();
system.out.println("result = " + result + ", and take up time : " + (endcounttime - startcounttime) / 1000 + "s");
}