java 内存比较,java在内存分配方面的效率比较

This may be a duplicate question but I couldnt find what I am searching. If it exists, sorry about duplication.

I want to learn that if the following part of codes are same in terms of memory allocation.

//first

int n = some_number;

for(int i = 0; i < n; i++){

for(int j = 0; j < n; j++){

int a = something;

}

}

//second

int i, j, a;

for(i = 0; i < n; i++){

for(j = 0; j < n; j++){

a = something;

}

}

I wonder, if java allocates the variable a n^2 times and j n times in the first code or both are allocated only once as in the second code.

I tried this couple of times in java but the results are inconsistent like in one trial first is 8 sec, second is 9 sec, in another trial reverse. So, I want to make sure if they are equal or not,

Thanks

解决方案

One easy way to see if there's a difference is to examine the bytecodes.

The first version compiles to:

public static void f();

Code:

0: bipush 100

2: istore_0

3: iconst_0

4: istore_1

5: goto 26

8: iconst_0

9: istore_2

10: goto 18

13: iconst_3

14: istore_3

15: iinc 2, 1

18: iload_2

19: iload_0

20: if_icmplt 13

23: iinc 1, 1

26: iload_1

27: iload_0

28: if_icmplt 8

31: return

whereas the second compiles to:

public static void g();

Code:

0: bipush 100

2: istore_3

3: iconst_0

4: istore_0

5: goto 26

8: iconst_0

9: istore_1

10: goto 18

13: iconst_3

14: istore_2

15: iinc 1, 1

18: iload_1

19: iload_3

20: if_icmplt 13

23: iinc 0, 1

26: iload_0

27: iload_3

28: if_icmplt 8

31: return

If you compare them closely, you'll see that they are essentially identical.

Stylistically, I think it's preferable to declare variables as close as possible to their first use. With this in mind, I'd choose the first version over the second.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值