Java - 在 for 循环中声明变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4501482/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 06:38:29  来源:igfitidea点击:

Java - Declaring variables in for loops

javamicro-optimization

提问by dfetter88

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

回答by Jason S

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

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

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

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

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.

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

回答by Matt Huggins

In both examples, you're going to instantiate a new string object that contains the string "Some String" the same number of times.

在这两个示例中,您将实例化一个新的字符串对象,该对象包含相同次数的字符串“Some String”。

In the first example where you declare strinside of the loop, all references to that string are going to be lost after the for-loop completes, allowing Java's garbage collector to remove all instances of the strings from memory. However, in the second example where you declare stroutside of the loop, the last string you created will still have a reference to it outside the loop, and Java's garbage collector will only remove 9 out of 10 of the strings from memory that were instantiated.

str循环内部声明的第一个示例中,在 for 循环完成后,对该字符串的所有引用都将丢失,从而允许 Java 的垃圾收集器从内存中删除字符串的所有实例。但是,在第二个示例中,您str在循环外声明,您创建的最后一个字符串在循环外仍将引用它,Java 的垃圾收集器只会从内存中删除已实例化的 10 个字符串中的 9 个。

As such, the first method is better since you do not hold onto any references of the string, interfering with the garbage collector's ability to determine if it's still in use.

因此,第一种方法更好,因为您不保留字符串的任何引用,干扰垃圾收集器确定它是否仍在使用中的能力。

回答by David Weiser

Beyond what @Jason S said, I'd also encourage you to think about the readability of the code.

除了@Jason S 所说的之外,我还鼓励您考虑代码的可读性。

For instance, if you are only writing to a reference once, it would make your intentmore clear to use something like:

例如,如果您只写一次参考文献,那么使用以下内容会使您的意图更加明确:

String str = "write once";
while(condition){
    //do stuff with str
}

Versus:

相对:

String str = null;
while(condition){
    str = "write once";
    //do stuff with str
}

Likewise, if the value of the string is reallybased off something that is specific to an iteration of the loop, declare the variable inside the loop.

同样,如果字符串的值确实基于特定于循环迭代的某些内容,请在循环内声明变量。

回答by jzd

The memory used by a variable reference is small. It is typically better practice to declare the item inside the loop because it will be closer to where it is used and more readable.

变量引用使用的内存很小。在循环内声明项目通常是更好的做法,因为它会更接近使用它的地方并且更具可读性。

回答by Falmarri

It depends. The inefficiency is from the overhead creating the String object, assuming your compiler doesn't change anything. The memory will be cleared once it goes out of scope.

这取决于。低效率来自创建 String 对象的开销,假设您的编译器没有改变任何东西。一旦超出范围,内存将被清除。