java装箱拆箱的运行性能问题

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.装箱拆箱和强制转换的效率比较其实差不了多少,属于同一数量级的。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值