public class main { public static void main(String[] args) throws Exception { autoboxing(); unboxing(); toObject(); toData(); integerTranfer(); intTranfer(); } public static void autoboxing(){ long starttime = System.currentTimeMillis(); Integer number; for(int i=0;i<100000000;i++){ number=i; } System.out.println("the autoboxing time is "+(System.currentTimeMillis()-starttime)+"ms"); } public static void unboxing(){ long starttime = System.currentTimeMillis(); int number; for(Integer i=0;i<100000000;i++){ number=i; } System.out.println("the unboxing time is "+(System.currentTimeMillis()-starttime)+"ms"); } public static void toObject(){ long starttime = System.currentTimeMillis(); Integer number; for(int i=0;i<100000000;i++){ number=(Integer)i; } System.out.println("the toObject time is "+(System.currentTimeMillis()-starttime)+"ms"); } public static void toData(){ long starttime = System.currentTimeMillis(); int number; for(Integer i=0;i<100000000;i++){ number=i.intValue(); } System.out.println("the toData time is "+(System.currentTimeMillis()-starttime)+"ms"); } public static void integerTranfer(){ long starttime = System.currentTimeMillis(); Integer number; for(Integer i=0;i<100000000;i++){ number=i; } System.out.println("the integerTranfer time is "+(System.currentTimeMillis()-starttime)+"ms"); } public static void intTranfer(){ long starttime = System.currentTimeMillis(); int number; for(int i=0;i<100000000;i++){ number=i; } System.out.println("the intTranfer time is "+(System.currentTimeMillis()-starttime)+"ms"); } } 结果为 the autoboxing time is 123ms the unboxing time is 698ms the toObject time is 107ms the toData time is 985ms the integerTranfer time is 660ms the intTranfer time is 2ms 由上代码分析可知: 1.基本数据类型的运算要远远快于装箱拆箱的运算(对象是不能直接运算的,它必须转换成基本类型再进行运算,然后再装箱成对象),在编程时,要尽量避免装箱拆箱和运算 同时进行。 2.装箱拆箱和强制转换的效率比较其实差不了多少,属于同一数量级的。