0

Top shows that R is using 3.5GB of memory.

After executing the following code:

rm(list=ls(all=TRUE))

the 3.5GB of resources were still in used by R.

How can we effectively empty all resources occupied by R?

lovalery
  • 4,524
  • 3
  • 14
  • 28
Mike Zhang
  • 21
  • 1
  • 3
    `rm` just deletes references to objects. To actually free memory occupied by previously referenced objects, you need to trigger a garbage collection with `gc`. That said, the most reliable approach is to quit and restart R. – Mikael Jagan Feb 18 '22 at 23:41
  • Actually I tried gc() after rm(list=ls(all=TRUE)). It just released a little bit of memory space (let's say 1MB). But it didnot release the 3.5GB of memory occupied by R. – Mike Zhang Feb 21 '22 at 22:24
  • See also: https://stackoverflow.com/questions/53333858/how-to-clean-up-r-memory-without-the-need-to-restart-r-session/70841811#70841811 – Mikael Jagan Feb 21 '22 at 22:40

1 Answers1

2

As Mikael Jagan said in a comment, calling gc() will immediately run the garbage collector and return memory from unreferenced objects to the operating system. However, you generally don’t have to do this, as memory will still be freed up when actually needed by R or other processes. In the meantime, that memory may still show as in use by R, because, as Hadley explains:

Both R and the operating system are lazy: they won’t reclaim memory until it’s actually needed. R might be holding on to memory because the OS hasn’t yet asked for it back.

For more, see the section on garbage collection in Advanced R.

zephryl
  • 14,633
  • 3
  • 11
  • 30