2

I started to use gc() for garbage collection in R. I have 16 GB RAM and sometimes, up to 10 GB RAM gets freed when using this command.

Does it make sense to use gc() inside functions? Often, the functions I write/use need almost all RAM that is available. Or does R reliably clean up memory that was used only inside a function?

Example:

f <- function(x) {
  # do something
  y <- doStuff(x)

  # do something else
  z <- doMoreStuff(y)

  # garbage collection
  gc()

  # return result
  return(z)
}
bask0
  • 340
  • 2
  • 11
  • 1
    Here is the post, that 42- mentions: http://stackoverflow.com/questions/1467201/forcing-garbage-collection-to-run-in-r-with-the-gc-command?lq=1 – lmo Apr 15 '16 at 12:01

1 Answers1

0

Calling gc() is largely pointless, as R calls it automatically when more memory is needed. The only reason I can think of for calling gc() explicitly is if another program needs memory that R is hogging.

Scott Warchal
  • 1,028
  • 10
  • 15
  • Thanks Swarch, didn't know this. A lot of people suggest to use it. – bask0 Apr 15 '16 at 10:11
  • 1
    [This](http://adv-r.had.co.nz/memory.html) chapter of Advanced R might be worth a read. – Scott Warchal Apr 15 '16 at 10:12
  • 3
    My experience appears to be different than hadley's. When I anticipate an update or a regression with a large data object (say an 10 GB object on a machine with 32GB) I will do a gc() before the operation. Otherwise my experience (on a Mac) is that the process will sometimes "spill over" into virtual memory and then I need to go out for coffee to await R's return. I know that Dirk has said the same. So you now have dualing authorities (Dirk versus hadley). – IRTFM Apr 15 '16 at 10:19
  • Thanks also for this input. I'll read both posts (Imo posted the link in a comment to my question to the other article mentioned by 42). – bask0 Apr 15 '16 at 12:44
  • 2
    I disagree that calling `gc()` manually is pointless. It can have a major impact on memory usage in my experience. – Max Masnick Aug 02 '17 at 19:48