# 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 '14 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 '14 at 21:05

As long as your string lives under Person Obejct and Person object is not eligible for GC, your string will never be collected. Also invocation of GC is not guaranteed. JVM manages it for you.

-

The first code snippet looks better for computer but second is better for human. I suggest to write understandable code and let the Java compiler do the optimization for you :) Believe me, compiler can do this job very well

-
What exactly is the difference for the computer? –  Simon André Forsberg Apr 25 '14 at 22:21
-1: It makes no difference whatsoever from a bytecode point of view. –  devoured elysium Apr 26 '14 at 3:07
-1: The java compiler (Eclipse's or javac) seldom does any kind of optimization. Optimizations, when happening, ocurr at the JIT compiler level. –  devoured elysium Apr 26 '14 at 3:12