From: Eric Hodel Date: 2005-10-10T05:20:49+09:00 Subject: Re: using lambda/Proc can prevent a lot of garbage collection On Oct 9, 2005, at 8:20 AM, David A. Black wrote: > Hi -- > > On Sun, 9 Oct 2005, Eric Mahurin wrote: > >> Here is an example where a Proc can cause a memory leak: >> >> ruby -e ' >> n=2**13;squares=(1..n).map{|i|a=(1..i).to_a;lambda{i*i}}; >> IO.readlines("/proc/#{Process.pid}/status").grep(/VmSize/).display' >> VmSize: 169312 kB >> >> You wouldn't expect each of these lambda's to need the local >> "a", but the binding holds it. Right now, the programmer needs >> to specifically think about this and clear these unexpected >> object references by hand: >> >> ruby -e ' n=2**13;squares = >> (1..n).map{|i|a=(1..i).to_a;f=lambda{i*i};a=nil;f}; >> IO.readlines("/proc/#{Process.pid}/status").grep(/VmSize/).display' >> VmSize: 10644 kB > > That's an interesting illustration, but I don't think I'd call it a > memory leak, since it's working as advertised. (At least, "memory > leak" to me implies something going wrong under the hood, so to > speak.) A closure should only enclose the variables needed for its execution. This is actually not very difficult but unfortunately eval('a') prevents Ruby from excluding unbound variables in closures. This is a (unfortunate IMO) feature of Ruby.