[R] Memory not release when an environment is created

Ismail SEZEN sezenismail at gmail.com
Thu Sep 22 18:45:37 CEST 2016


> On 22 Sep 2016, at 18:41, Olivier Merle <oliviermerle35 at gmail.com> wrote:
> 
> Dear,
> 
> When I use big data for a temporary use it seems that the memory is not
> released when a function/environement is created nearby.
> Here the reproducible exemple:
> 
> test<-function(){
> x=matrix(0,50000,10000)
> y=function(nb) nb^2
> return(y)
> }
> xx=test() # 3 Go of Ram is used
> gc() # Memory is not released !! even if x has been destroyed [look into
> software mem used]

Because y is a function and returns with its own environment.

ls(environment(xx)) # x and y objects are still there

> How can I release the data in test without destroying the xx object ? As x
> which is big object is destroyed, I though I could get my memory back but
> it seems that the function y is keeping the x object.

if you do not need the x object in y function then remove it in it’s own environment as follows;

> test<-function(){
> x=matrix(0,50000,10000)
   rm(x)
> y=function(nb) nb^2
> return(y)
> }

or if you need to remove it out of the function;

rm("x", envir = environment(xx))
ls(environment(xx)) # x has gone

 If y function uses x somehow, then you will need to live with a big object.


More information about the R-help mailing list