Garbage collection in generators

Benjamin Gruenbaum benjamingr at gmail.com
Wed Feb 17 08:59:07 UTC 2016


On Wed, Feb 17, 2016 at 10:51 AM, Andreas Rossberg <rossberg at google.com>
wrote:

> On 17 February 2016 at 09:40, Benjamin Gruenbaum <benjamingr at gmail.com>
> wrote:
>
>> If you starve a generator it's not going to get completed, just like
>>> other control flow won't.
>>>
>>
>> I'm not sure starving is what I'd use here - I definitely do see users do
>> a pattern similar to:
>>
>> ```js
>> function getResults*() {
>>      try {
>>          var resource = acquire();
>>          for(const item of resource) yield process(item);
>>      } finally {
>>          release(resource);
>>      }
>> }
>> ```
>>
>
> Yes, exactly the kind of pattern I was referring to as "bogus forms of
> resource management". This is an anti-pattern in ES6. It won't work
> correctly. We should never have given the illusion that it does.
>

What is or is not an anti-pattern is debatable. Technically if you call
`.return` it will run the finally block and release the resources (although
if the finally block itself contains `yield` those will also run).
Effectively, this will have the same sort of consequences that "acquire()"
and "release()" had to begin with - so I would not say it makes things
worse but I definitely agree that it creates a form of false expectation.

Still - I'm very curious why languages like Python have chosen to call
`finally` blocks in this case - this was not a hindsight and according to
the PEP. They debated it and explicitly decided to call `release`. I'll see
if I can email the people involved and ask about it.



> garbage collection is a form of automatic resource management.
>
>
> Most GC experts would strongly disagree, if by resource you mean anything
> else but memory.
>

Memory is most certainly a resource. Languages that are not GCd like C++
really don't make the distinction we make :)

Garbage collection can and does in fact manage resources in JavaScript host
environments right now. For example, an XMLHttpRequest *may *abort the
underlying HTTP request if the XMLHttpObject is not referenced anywhere and
gets garbage collected.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20160217/af00fdd0/attachment.html>


More information about the es-discuss mailing list