自动装箱、拆箱的时间消耗
2022-09-22 22:49:05

装箱就是自动将基本数据类型转换为包装器类型: 比如 int-> Integer
拆箱就是自动将包装器类型转换为基本数据类型: 比如 Integer -> int

对比耗时

1. 使用自动装箱、拆箱

用for循环,从1-1亿 进行累加

1
2
3
4
5
6
7
8
9
10
11
public static void test1(){
long start = System.currentTimeMillis();
//包装类型
Long sum = 0L;
for (long i = 0; i < 10_0000_0000; i++) {
sum += i;
}
System.out.println("sum==> " + sum);
long end = System.currentTimeMillis();
System.out.println("Test1 :take " + (end - start)/1000.0f + " seconds");
}

耗时
sum==> 499999999500000000
Test1 :take 5.892 seconds

2. 不使用自动装箱、拆箱

1
2
3
4
5
6
7
8
9
10
11
public static void test1(){
long start = System.currentTimeMillis();
//普通类型
long sum = 0L;
for (long i = 0; i < 10_0000_0000; i++) {
sum += i;
}
System.out.println("sum==> " + sum);
long end = System.currentTimeMillis();
System.out.println("Test1 :take " + (end - start)/1000.0f + " seconds");
}

耗时
sum==> 499999999500000000
Test1 :take 0.74 seconds

3. 结论

  • 频繁的自动装箱、拆箱会耗费大量的时间
  • 在执行大量运算的时候,尽量使用普通类型进行运算,在结果处使用包装类型即可

原因探究

自动装箱

比如在执行Long l = 100 的时候,实际上执行了 Long.valueOf(100)

1
2
3
4
5
6
7
8
9
//valueOf源码
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);
}

也就是说在 -128~127之间是从缓存里取出的。一旦超出了这个范围就会创建一个Long的对象。所以装箱的过程会增加内存的消耗,影响性能。

这个创建对象的过程就是耗费时间的原因所在。执行上面的代码不断创建了Long的对象,自然执行之间会久一些。

自动拆箱

Long obj= 100;
long l = obj;(此处自动拆箱)
实际上调用了 obj.longValue();方法

1
2
3
4
5
6
7
8
//源码
/**
* Returns the value of this {@code Long} as a
* {@code long} value.
*/
public long longValue() {
return value;
}
Prev
2022-09-22 22:49:05
Next