Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
265 views
in Technique[技术] by (71.8m points)

micro optimization - Java - Declaring variables in for loops

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";
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...