HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavaModerate

How do I avoid over-using the garbage collector?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thecollectoravoidusinghowgarbageover

Problem

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
    }
}

Solution

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.

Context

StackExchange Code Review Q#48193, answer score: 14

Revisions (0)

No revisions yet.