问题
Is there any difference between
for (...) {
String temp = "temp";
}
and
String temp;
for (...) {
temp = "temp";
}
I mean, does Java waste many resources creating/deleting objects in loop?
Thank you.
回答1:
The difference is in scope of variable.
Defined inside loop means visible only inside the loop.
Defined outside the loop means visible inside and outside the loop.
does Java waste many resources creating/deleting objects in loop?
if defined inside the loop then it will be re-intialized with every iteration, which means an extra executable statement. If you want to re-intialize it with each iteration then good otherwise move it out to save wasted cpu for that statement.
回答2:
The only difference is the issue of scope. With the variable being declared outside the for-block, the variable (object reference) can be accessed outside the for-loop block.
If the object reference variable is declared inside the for-loop, then it can only be accessed within the for-loop block.
回答3:
First the two scope variables.
- define inside the loop will be visible only to loop.
- define outside the loop will be visible to inside and outside the loop
Java waste many resources creating/deleting
Java creates as many objects of String as many times you are iterating your loop but the reference will be same. So its a bit resource and memory consuming. Use StringBuilder or StringBuffer.
回答4:
for (...)
{
String temp = "temp";
}
In this case your temp would be available only for For loop
String temp;
for (...)
{
temp = "temp";
}
And here If you are writing this code inside a method then it would be available throughout the method.
Note:- Local variables are created in Stack and are removed after execution of that method.
来源:https://stackoverflow.com/questions/21020432/java-declaring-objects-in-a-loop