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.
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.
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.
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.
First the two scope variables.
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
.
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.