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?