[R] Memory not release when an environment is created

David Winsemius dwinsemius at comcast.net
Thu Sep 22 19:57:46 CEST 2016


> On Sep 22, 2016, at 9:45 AM, Ismail SEZEN <sezenismail at gmail.com> wrote:
> 
> 
>> 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

That's much clearer than my `eval(quote(...` approach. I had forgotten that `rm` had an 'environment' parameter. I had considered trying:

environment(xx)$x <- NULL   # but after looking at `environment`'s help page I was pretty sure it would have failed 

# But there again I was wrong:

test<-function(){
x=matrix(0,500,100)
y=function(nb) nb^2
return(y)
}
xx=test()

environment(xx)$x <- NULL


> object.size( get("x", envir=environment(xx) ) )
0 bytes

I still think rm() is the way to go but this offers another illustration of available methods of environment mangling, er, manipulation.

Best;
David.


> 
> If y function uses x somehow, then you will need to live with a big object.
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

David Winsemius
Alameda, CA, USA



More information about the R-help mailing list