java怎么循环实例化,Java:在循环中实例化变量:好或坏样式?

Ive got one simple question. Normally I write code like this:

String myString = "hello";

for (int i=0, i<10; i++)

{

myString = "hello again";

}

Because I think the following would not be good style cause it would create too many unnecessary objects.

for (int i=0, i<10; i++)

{

String myString = "hello again";

}

Is this even correct? Or is this just the case when Ive got an explicit object like an object from a class I created? What if it was a boolean or an int? What is better coding style? Instantiate it once before the loop and use it in the loop or instantiate it every time in the loop again? And why? Because the program is faster or less storage is used or...?

Some one told me, if it was a boolean I should instantiate it directly in the loop. He said it would not make a difference for the heap and it would be more clear that the variable belongs inside the loop. So what is correct?

Thanks for an answer! :-)

====

Thanks for all your answers!

In conclusion: it is preferable to declare an object inside the smallest scope possible. There are no performance improvements by declaring and instantiating objects outside the loop, even if in every looping the object is reinstantiated.

解决方案

No, the latter code isn't actually valid. It would be with braces though:

for (int i=0; i<10; i++)

{

String myString = "hello again";

}

(Basically you can't use a variable declaration as a single-statement body for an if statement, a loop etc.)

It would be pointless, but valid - and preferable to the first version, IMO. It takes no more memory, but it's generally a good idea to give your local variables the narrowest scope you can, declaring as late as you can, ideally initializing at the same point. It makes it clearer where each variable can be used.

Of course, if you need to refer to the variable outside the loop (before or afterwards) then you'll need to declare it outside the loop too.

You need to differentiate between variables and objects when you consider efficiency. The above code uses at most one object - the String object referred to by the literal "hello again".

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值