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";
}
Often the variable that controls a for loop is needed only for the purposes of the loop and is not used elsewhere. When this is the case, it is possible to declare the variable inside the initialization portion of the for.
But in the name of best coding practice it is recommended to declare the variable in the smallest possible scope (in this example it is inside the loop, as this is the only place where the variable is used).
It's not a problem to define a variable within a loop. In fact, it's good practice, since identifiers should be confined to the smallest possible scope. What's bad is to assign a variable within a loop if you could just as well assign it once before the loop runs.
In Java, multiple variables can be initialized in the initialization block of for loop regardless of whether you use it in the loop or not.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With