JAVA中for循环覆盖数组,在Java中的for循环中声明数组有多糟糕?

I come from a C background, so I admit that I'm still struggling with letting go of memory management when writing in Java. Here's one issue that's come up a few times that I would love to get some elaboration on. Here are two ways to write the same routine, the only difference being when double[] array is declared:

Code Sample 1:

double[] array;

for (int i=0; i

array = calculateSomethingAndReturnAnArray(i);

if (someFunctionOnArrays(array)) {

// DO ONE THING

} else {

// DO SOME OTHER THING

}

}

Code Sample 2:

for (int i=0; i

double[] array = calculateSomethingAndReturnAnArray(i);

if (someFunctionOnArrays(array)) {

// DO ONE THING

} else {

// DO SOME OTHER THING

}

}

Here, private double[] calculateSomethingAndReturnAnArray(int i) always returns an array of the same length. I have a strong aversion to Code Sample 2 because it creates a new array for each iteration when it could just overwrite the existing array. However, I think this might be one of those times when I should just sit back and let Java handle the situation for me.

What are the reasons to prefer one of the ways over the other or are they truly identical in Java?

解决方案

There's nothing special about arrays here because you're not allocating for the array, you're just creating a new variable, it's equivalent to:

Object foo;

for(...){

foo = func(...);

}

In the case where you create the variable outside the loop it, the variable (which will hold the location of the thing it refers to) will only ever be allocated once, in the case where you create the variable inside the loop, the variable may be reallocated for in each iteration, but my guess is the compiler or the JIT will fix that in an optimization step.

I'd consider this a micro-optimization, if you're running into problems with this segment of your code, you should be making decisions based on measurements rather than on the specs alone, if you're not running into issues with this segment of code, you should do the semantically correct thing and declare the variable in the scope that makes sense.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值