From: Rick DeNatale Date: 2008-01-11T07:00:49+09:00 Subject: Re: why does this code leak? On 1/10/08, Radosław Bułat wrote: > On Jan 10, 2008 10:15 PM, Robert Dober wrote: > > I honestly fail to see why the closure shall take a reference to the > > object . I am with Ara here, no need to keep a reference to the object > > and this is not only MHO but also that one of Ruby1.9;), if not a bug > > at least it is odd behavior. > > I thought the same at first time. Read > http://ola-bini.blogspot.com/2007/12/ruby-closures-and-memory-usage.html > and you should change opinion. > > 2 comments from post: > "Many languages have compilers that perform analysis on the closures > and capture only the variables it actually closes on; This includes > the "self" variable of the instance. This is not currently the case > with Ruby? Is there any reason why the compiler could not be > implemented in such a way?" > > Ola response: > "Tomas: yes, there is a marvelous reason for this: eval. There is no > way for the parser to know which variables will be used at any point. > The price you pay for a VERY dynamic language." But this is a mis-analysis. Just because you can dynamicaly eval a string at run-time doesn't mean that the compiler can't perform analysis on code producing a block whether it's done at 'compile-time' or 'execution-time' which in Ruby are actually the same time anyway. Doing optional optimizations based on analysis of the actual code is something commonly done in advance implementations of dynamic languages. Some languages do this optimization later than others. Smalltalk for example DOES have what is in effect separate compile and execute times, and Smalltalk sometimes restricts the program so as to allow optimizations such as turning expression ifTrue: [x] ifFalse:[y] into test and branch logic instead of the method send it appears to be. Other languages like self, do these optimizations much later, often AFTER partial execution deferring them until the VM notices that a particular code path is frequently executed and would benefit, and these kinds of techniques go far beyond what would be required for the Ruby compiler/VM to analyze a block for references before reifiying a proc. Having said all this, I would urge caution, because such implementation approaches work best when accomplished by careful cost-benefit analysis. -- Rick DeNatale My blog on Ruby http://talklikeaduck.denhaven2.com/