# How do I avoid over-using the garbage collector?

I'm wondering what the best way of initializing variables so that I don't over use the garbage collector with a for-loop. Assuming the variable is only used inside the for-loop. Is it better to declare the variable outside of the for-loop?

public void foo() {
String tempName;
for (Person person : personList) {
tempName = person.getName();

//Do work with name
}
}


Or inside the for-loop?

public void foo() {
for (Person person : personList) {
String tempName = person.getName();

//Do work with name
}
}

-

For the Garbage Collector, it doesn't matter at all. You don't create the object. You just use an object reference to it in the above code.

The String object itself is still stored in the Person class and is therefore not garbage-collected until it is changed inside the Person object, or the Person object itself is garbage collected (which will happen when the Person does not have any more references to it).

Normally, you don't need to worry about "over-using" the Garbage Collector.

However, for the sake of readability it is a good practice to declare the variable in the smallest scope as possible. Therefore, I would go with the inside the for-loop approach.

-
To be accurate, String object is not stored in the Person class. The String object is lying on the heap and all references to it are equal. There is no notion of ownership of any object on the heap. –  Teddy Jul 3 at 21:04
@Teddy I did not want to imply ownership. Perhaps "referenced" would be a better word instead of "stored"? –  Simon André Forsberg Jul 3 at 21:05