4
\$\begingroup\$

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
    }
}
\$\endgroup\$

3 Answers 3

14
\$\begingroup\$

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.

\$\endgroup\$
2
  • \$\begingroup\$ 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. \$\endgroup\$
    – Teddy
    Jul 3, 2014 at 21:04
  • \$\begingroup\$ @Teddy I did not want to imply ownership. Perhaps "referenced" would be a better word instead of "stored"? \$\endgroup\$ Jul 3, 2014 at 21:05
2
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$

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

\$\endgroup\$
3
  • 2
    \$\begingroup\$ What exactly is the difference for the computer? \$\endgroup\$ Apr 25, 2014 at 22:21
  • 1
    \$\begingroup\$ -1: It makes no difference whatsoever from a bytecode point of view. \$\endgroup\$ Apr 26, 2014 at 3:07
  • \$\begingroup\$ -1: The java compiler (Eclipse's or javac) seldom does any kind of optimization. Optimizations, when happening, ocurr at the JIT compiler level. \$\endgroup\$ Apr 26, 2014 at 3:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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