Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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
    }
}
share|improve this question
add comment

3 Answers 3

up vote 14 down vote accepted

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.

share|improve this answer
    
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
add comment

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.

share|improve this answer
add comment

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

share|improve this answer
2  
What exactly is the difference for the computer? –  Simon André Forsberg Apr 25 at 22:21
1  
-1: It makes no difference whatsoever from a bytecode point of view. –  devoured elysium Apr 26 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 at 3:12
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.