Tim Kuipers
Tim Kuipers

Reputation: 1764

Optimizing reiterated array allocation

Consider these similar pieces of code:

for (int iteration = 0; iteration<a_lot; iteration++) {
    int[] re = new int[large];
    for (int i = 0; i<large; i++)
        re[i] = computeValue();
    ...
}

and

int[] re = new int[large];
for (int iteration = 0; iteration<a_lot; iteration++) {
    for (int i = 0; i<large; i++)
        re[i] = computeValue();
    ...
}

In the first example we reallocate new space for the array in each iteration and let the garbage collector deal with freeing up the space of the array in the previous iteration, while in the second example we reuse the same array. I can imagine that in some circumstances the first algorithm causes (or contributes to) a StackOverflowException, while the downside of the second algorithm is that the array is never garbage collected in between iterations, even though it might be the case that after some point in the iteration the array isn't used anymore.

In which circumstances is it better to use which algorithm?

Upvotes: 0

Views: 84

Answers (2)

user1196549
user1196549

Reputation:

Unless your array is so huge that it MUST be deallocated on every iteration, I see no benefit to reallocate it every time.

Upvotes: 1

Eugene
Eugene

Reputation: 120858

First, why do you think you'll get a StackOverflowException? The array will be stored on the heap(the reference will be on the stack). Second, GC is smart enough to clean memory in both cases. Actually as soon as the reference is not needed, Garbage Collector can recall the memory (it can recall memory, while being still in method.)

Upvotes: 1

Related Questions