Java:在循环中实例化变量:好或坏样式? [英] Java: instantiate variables in loop: good or bad style?

查看:704
本文介绍了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";
}

这是否正确?或者是这种情况下,当Ive有一个显式对象像一个对象从我创建的类?如果它是一个布尔值或int?什么是更好的编码风格?在循环之前实例化一次,并在循环中使用它,或者每次在循环中实例化它?为什么?因为程序更快或者使用更少的存储,或者...?

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! :-)

====

感谢您所有的答案!

结论:最好在最小范围内声明一个对象。通过在循环外声明和实例化对象,没有性能改进,即使在每次循环对象被重新赋值时。

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";
}

(基本上你不能将变量声明用作单语句对于 if 语句,循环等)

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

这将是无意义的,首选到第一个版本,IMO。它不需要更多的内存,但是通常一个好主意是给你的局部变量你可以最窄的范围,尽可能晚的声明,理想的初始化在同一点。

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.

当您考虑效率时,您需要区分变量对象。上面的代码至多使用了一个对象 - 字符串对象引用的字符串hello again。

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".

这篇关于Java:在循环中实例化变量:好或坏样式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆