java自动拆装箱的错误使用

 

今天有朋友问Integer a = 10;的内存使用,随便带出了自动拆装箱问题,以整型为例子进行说明

1、自动装箱

@Test
public void fun1() {
	Integer Ii = null;
	int ii = 0;
	long s = System.currentTimeMillis();
	for (int i = 0; i < 100000; i++) {
		Ii = i;
	}
	long e = System.currentTimeMillis();
	System.out.println(e - s);
	s = System.currentTimeMillis();
	for (int i = 0; i < 100000; i++) {
		ii = i;
	}
	e = System.currentTimeMillis();
	System.out.println(e - s);
}

第一次运行结果:
3

第二次运行结果:
2

第三次运行结果:
3
0

可以得出Integer Ii = int i比int ii = int i慢,运行10w次相差了3毫秒左右,主要原因是编译器在编译时进行了自动装箱操作,查看编译后源码就不难理解

  @Test
  public void fun1()
  {
    Integer Ii = null;
    int ii = 0;
    long s = System.currentTimeMillis();
    for (int i = 0; i < 100000; i++) {
      Ii = Integer.valueOf(i); // 将Integer Ii = 10;编译为Integer Ii =
                               Integer.valueOf(10);使用Integer.valueOf进行装箱
    }
    long e = System.currentTimeMillis();
    System.out.println(e - s);
    s = System.currentTimeMillis();
    for (int i = 0; i < 100000; i++) {
      ii = i;
    }
    e = System.currentTimeMillis();
    System.out.println(e - s);
  }

2、自动拆箱

@Test
public void fun2() {
	Integer Ii = null;
	int ii = 0;
	List list = new ArrayList();

	for (int i = 0; i < 100000; i++) {
		list.add(i);
	}
	long s = System.currentTimeMillis();
	for (int i = 0; i < list.size(); i++) {
		Ii = list.get(i);
	}
	long e = System.currentTimeMillis();
	System.out.println(e - s);

	s = System.currentTimeMillis();
	for (int i = 0; i < list.size(); i++) {
		ii = list.get(i);
	}
	e = System.currentTimeMillis();
	System.out.println(e - s);
}

第一次运行结果:
1

第二次运行结果:
2

第三次运行结果:
2
1

虽然计算时间相差不大,但依然能说明问题,多了一次拆箱过程10w次计算慢了将近1毫秒左右,编译后源码如下

  @Test
  public void fun2() {
    Integer Ii = null;
    int ii = 0;
    List list = new ArrayList();

    for (int i = 0; i < 100000; i++) {
      list.add(Integer.valueOf(i));
    }
    long s = System.currentTimeMillis();
    for (int i = 0; i < list.size(); i++) {
      Ii = (Integer)list.get(i);
    }
    long e = System.currentTimeMillis();
    System.out.println(e - s);

    s = System.currentTimeMillis();
    for (int i = 0; i < list.size(); i++) {
      ii = ((Integer)list.get(i)).intValue();// 将Integer对象使用intValue进行拆箱

    }
    e = System.currentTimeMillis();
    System.out.println(e - s);
  }

3、总结:应该尽量避免这种错误的拆装箱的使用,统一类型,尽量使用基本数据类型,写程序时要考虑是否会出现自动拆装箱

ps:尽量使用基本数据类型,基本数据类型为栈内存操作,利于内存回收,速度也更快。使用int a = 10;代替Integer a = 10;

http://blog.shilimin.com/324.htm

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值