Java - 在for循环中声明变量 [英] Java - Declaring variables in for loops

查看:261
本文介绍了Java - 在for循环中声明变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在循环中声明一个变量是不好的做法?在我看来,这样做,如下面的第一个代码块所示,将使用十倍的内存作为第二个...由于在循环的每次迭代中创建一个新的字符串。这是正确的吗?

Is declaring a variable inside of a loop poor practice? It would seem to me that doing so, as seen in the first code block below, would use ten times the memory as the second... due to creating a new string in each iteration of the loop. Is this correct?

for (int i = 0; i < 10; i++) {
  String str = "Some string";
}

vs。

String str;
for (int i = 0; i < 10; i++) {
  str = "Some String";
}


推荐答案


在循环中声明一个变量是不好的做法?

Is declaring a variable inside of a loop poor practice?

完全没有!它将变量本地化为其使用点。

Not at all! It localizes the variable to its point-of-use.


在我看来这样做,如第一个代码块中所示下面,将使用十倍的内存作为第二个

It would seem to me that doing so, as seen in the first code block below, would use ten times the memory as the second

编译器可以优化事物以保持内存使用效率。仅供参考:如果您使用 final 关键字告诉它您的变量对某个对象有固定的引用,您可以提供帮助。

The compiler may optimize things to keep memory use efficient. FYI: you can help it, if you use the final keyword to tell it that your variable has a fixed reference to an object.

注意:如果你有一个更复杂的对象,你在构造函数中执行复杂的代码,那么你可能需要担心单次执行和多次执行,并在循环之外声明对象。

Note: if you have a more complex object where you are executing complex code in the constructor, then you may need to worry about single vs. multiple executions, and declare the object outside of the loop.

这篇关于Java - 在for循环中声明变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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