java装箱拆箱的运行性能问题
2015-10-09 11:00
771 查看
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.装箱拆箱和强制转换的效率比较其实差不了多少,属于同一数量级的。
相关文章推荐
- java对世界各个时区(TimeZone)的通用转换处理方法(转载)
- java-注解annotation
- java-模拟tomcat服务器
- java-用HttpURLConnection发送Http请求.
- java-WEB中的监听器Lisener
- Android IPC进程间通讯机制
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- 介绍一款信息管理系统的开源框架---jeecg
- 聚类算法之kmeans算法java版本
- java实现 PageRank算法
- PropertyChangeListener简单理解
- 插入排序
- 冒泡排序
- 堆排序
- 快速排序
- 二叉查找树
- [原创]java局域网聊天系统