1

I have a large object in my R environment declared as, say, X. Now, I would like to remove that object from my environment in order to make space in memory for another large object, say, Z created by some function, say, Y. In my mind, I have two ways to do this. I can remove X first and then create my new object: Z <- Y(..). Or, instead of calling my new object Z, I can call it X: X <- Y(..). The latter way basically replaces the old object with the new.

Now to my question, If I were to apply the latter method does R first remove X before applying function Y to create the new object or does R create the new object first and only then removes the old object?

Sven Hohenstein
  • 80,497
  • 17
  • 145
  • 168
nrcjea001
  • 1,027
  • 1
  • 9
  • 21
  • 3
    What you are asking about is heavily influenced by the discussion of *garbage collection*. Even when you execute `rm(X)`, there is no guarantee of immediate availability of memory (for that, see [`?gc`](https://stat.ethz.ch/R-manual/R-devel/library/base/html/gc.html)). So, "does R first remove X", the answer is "unlikely"; to "does R create the new object first", I suggest "likely", though the old object removal will likely happen "eventually", once R realizes that it is no longer referenced. (Suggests http://stackoverflow.com/questions/8813753/what-is-the-difference-between-gc-and-rm .) – r2evans Jan 24 '17 at 06:47
  • 4
    It depends a lot on the context, and when `gc` gets called (over which you have limited control). If you're using `X` as a preallocated structure, you're merely changing values instead of deallocating and reallocating memory. On the other end, your function likely creates temporary variables, which allocate additional memory, which if your data is large may be large themselves. To figure out more of what's actually happening, profile your code. The recent integration of `profvis` into RStudio makes doing so pretty easy. – alistaire Jan 24 '17 at 07:13

0 Answers0