自动装箱、拆箱的时间消耗
2022-09-22 22:49:05
装箱就是自动将基本数据类型转换为包装器类型: 比如 int-> Integer
拆箱就是自动将包装器类型转换为基本数据类型: 比如 Integer -> int
对比耗时
1. 使用自动装箱、拆箱
用for循环,从1-1亿 进行累加
1 | public static void test1(){ |
耗时
sum==> 499999999500000000
Test1 :take 5.892 seconds
2. 不使用自动装箱、拆箱
1 | public static void test1(){ |
耗时
sum==> 499999999500000000
Test1 :take 0.74 seconds
3. 结论
- 频繁的自动装箱、拆箱会耗费大量的时间
- 在执行大量运算的时候,尽量使用普通类型进行运算,在结果处使用包装类型即可
原因探究
自动装箱
比如在执行Long l = 100 的时候,实际上执行了 Long.valueOf(100)
1 | //valueOf源码 |
也就是说在 -128~127之间是从缓存里取出的。一旦超出了这个范围就会创建一个Long的对象。所以装箱的过程会增加内存的消耗,影响性能。
这个创建对象的过程就是耗费时间的原因所在。执行上面的代码不断创建了Long的对象,自然执行之间会久一些。
自动拆箱
Long obj= 100;
long l = obj;(此处自动拆箱)
实际上调用了 obj.longValue();方法
1 | //源码 |