自动装箱和自动拆箱是java5.0版本引入的,能自动将基本类型转换为对应的基本类型包装对象,那么我们比较一下他们的性能情况。
package com.wmmad.test;
import junit.framework.TestCase;
/**
* @author madding.lip
*
*
* class: compare the autoboxing and unboxing and normal's performance
*
*
*/
@SuppressWarnings("unused")
public class BoxTest extends TestCase {
public static void main(String[] args) {
testAutoboxing();
testUnboxing();
testChangeToObject();
testChangeToData();
testNormal();
testNormal1();
}
public static void testAutoboxing() {
long start = System.currentTimeMillis();
Integer result = 0;
for (int i = 0; i < 1000000000; i++) {
result = i; // autoboxing
}
long end = System.currentTimeMillis();
System.out.println("autoboxing use time is: " + (end - start) + "ms");
}
public static void testUnboxing() {
int result = 0;
long start = System.currentTimeMillis();
for (Integer i = 0; i < 1000000000; i++) {
result = i;
}
long end = System.currentTimeMillis();
System.out.println("unboxing use time is: " + (end - start) + "ms");
}
public static void testChangeToObject() {
Integer result = 0;
long start = System.currentTimeMillis();
for(int i = 0; i < 1000000000; i++) {
result = (Integer)i;
}
long end = System.currentTimeMillis();
System.out.println("change to object use time is: " + (end - start) + "ms");
}
public static void testChangeToData() {
int result = 0;
long start = System.currentTimeMillis();
for(Integer i = 0; i < 1000000000; i++) {
result = i.intValue();
}
long end = System.currentTimeMillis();
System.out.println("change to data use time is: " + (end - start) + "ms");
}
public static void testNormal() {
int result = 0;
long start = System.currentTimeMillis();
for (int i = 0; i < 1000000000; i++) {
result = i;
}
long end = System.currentTimeMillis();
System.out.println("normal use time is: " + (end - start) + "ms");
}
public static void testNormal1() {
Integer result = 0;
long start = System.currentTimeMillis();
for (Integer i = 0; i < 1000000000; i++) {
result = i;
}
long end = System.currentTimeMillis();
System.out.println("normal1 use time is: " + (end - start) + "ms");
}
}
/**
* result:
* autoboxing use time is: 6420ms
* unboxing use time is: 7297ms
* change to object use time is: 6929ms
* change to data use time is: 7089ms
* normal use time is: 2ms
* normal1 use time is: 6847ms
*/
从运行的结果可以得出几个结论:
1.对象之间的赋值和自动装拆箱差不多;
2.自动装箱贺自动拆箱的性能差不多;
3.基本数据类型的运算是远远快于对象以及自动装拆箱;
上面的例子只是针对赋值操作的结果。在java代码编写过程中,很多时候需要操作对象而不是基本数据类型,这样我们不得不进行基本类型转对象,因此我们必须评估对象转换的成本大还是自动装箱性能消耗大,我试过了把基本类型通过自动装箱和转成对象,结果发现性能差不多。
使用原则:
1.能不用对象尽量不用,因为基本类型的运算远远快于对象的运算;
2.不得不用对象时,采用自动装箱或手动转性能差不了多少;