Skip to content
Prev 314029 / 398506 Next

Memory filling up while looping

On 12-12-20 6:26 PM, Peter Meissner wrote:
You should pre-allocate your result matrix.  By growing it a few rows at 
a time, R needs to do this:

allocate it
allocate a bigger one, copy the old one in
delete the old one, leaving a small hole in memory
allocate a bigger one, copy the old one in
delete the old one, leaving a bigger hold in memory, but still too small 
to use...

etc.

If you are lucky, R might be able to combine some of those small holes 
into a bigger one and use that, but chances are other variables will 
have been created there in the meantime, so the holes will go mostly 
unused.  R never moves an object during garbage collection, so if you 
have fragmented memory, it's mostly wasted.

If you don't know how big the final result will be, then allocate large, 
and when you run out, allocate bigger.  Not as good as one allocation, 
but better than hundreds.

Duncan Murdoch