I’ve a program where the loop in question looks something like this
int numOfWords = 1000;
int avgSizeOfWord = 20;
while(all documents are not read) {
char[][] wordsInDoc = new char[numOfWords][avgSizeOfWord];
for(int i=0; i<numWordsInDoc; i++) {
wordsInDoc[i] = getNextWord();
}
processWords(wordsInDoc);
}
I was wondering what happens behind the scene when this loop gets executed. When does the garbage collector collect the memory that has been assigned for each document? Is their a better way (wrt memory usage) to do the same?
Any insight is appreciated.
Well you’re definitely wasting memory – you’re allocating all of the “sub-arrays” and then overwriting them. You’d be better off with:
Now what does
processWordsactually do? If it doesn’t stash the array anywhere, you could reuse it:I would definitely perform the first change, but probably not the second.
As for when exactly garbage collection occurs – that’s implementation-specific.