18

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";
}
3
  • 2
    String is immutable class that always create new instance on write. But your case, it is possible optiminized by compiler because of the constant value. Commented Dec 21, 2010 at 16:31
  • Maybe string was a poor choice for this example then. My real question is... if a variable is declared inside a loop, is a new variable declared for each iteration, or is this optimized by the compiler into a single variable? Commented Dec 21, 2010 at 16:36
  • 3
    variable declaration and object construction are two separate things. If you did final Foo foo = new Foo(someArg); inside the loop which executed N times, it would construct N separate objects, vs. outside the loop where it would execute once. But if you had final Foo foo1 = new Foo(someArg); outside the loop, and then final Foo foo = foo1 inside the loop, you would only have 1 object instantiated. Strings are kind of special, since they are immutable constants, and the compiler would likely optimize it into creating one String object, and re-using it each time in the loop. Commented Dec 21, 2010 at 16:53

5 Answers 5

26

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.

Sign up to request clarification or add additional context in comments.

6 Comments

Just a followup.. What if we had String str = new String("Some String"); in the loop? My understanding is that it would create 10 instances!
@Ravi: you're probably right, because you're explicitly calling the String constructor, which I am fairly certain bypasses the string interning operation that re-uses constant String instances.
But even in that case, if you move the declaration of str outside the loop, and left the assignment inside the loop, you would still create the same 10 instances.
@ILMTitan: Yeah, you are right. I just wanted to know if JVM optimizes even if have a new operator.
It would create ten instances, yes, but you'd have to do that over nine thousand times to get any significant performance impact. Keeping the variable in scope allows the runtime to free that variable quickly (and re-use it across iterations) - moving the variable to the surrounding scope will keep it in memory longer. And you'd still re-create the object instance for each iteration regardless.
|
7

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

In the first example where you declare str inside 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 str outside 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.

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.

Comments

2

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

For instance, if you are only writing to a reference once, it would make your intent more 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 really based off something that is specific to an iteration of the loop, declare the variable inside the loop.

Comments

1

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.

2 Comments

The memory used by a variable reference is indeed small. But if the loop iterates from 0 to 10000000000, and using code block #2 only uses one variable reference (as opposed to one for each iteration for block #1), you can surely see that this would be an issue.
Yes even if you looping that many times this should not make much of a difference. As others have said the compiler might even optimize it out, you can test it and see for sure. But either way the cost in making the code harder to read is not worth a very minor performance improvement.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.