Garbage collection in generators

Benjamin Gruenbaum benjamingr at
Wed Feb 17 08:40:41 UTC 2016

On Wed, Feb 17, 2016 at 10:28 AM, Andreas Rossberg <rossberg at>
> The spec does not talk about GC, but in typical implementations you should
> expect yes.

Yes, important point since some ECMAScript implementations don't even have
GC and are just run to completion. The spec doesn't require cleanup.

 - If it is - does it run the `finally` blocks?
> No, definitely not. Try-finally has nothing to do with GC, it's just
> control flow.

I'm not sure that "has nothing to do" is how I'd put it. try/finally is
commonly used for resource management and garbage collection is a form of
automatic resource management. There is also the assumption that finally is
always run. Two other languages have opted into the "run finally" behavior
so I wouldn't call it crazy although I tend to agree with the conclusion.

> 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:

function getResults*() {
     try {
         var resource = acquire();
         for(const item of resource) yield process(item);
     } finally {

They would then do something like:

var res = getResults();
var onlyCareAbout = Array.from(take(10, res));
// ignore res from this point on.

Now, in a for.. of loop with a break - `return` would be called freeing the
resource - in this case the resource would stay "held up" forever - users
can call `.return` explicitly on the generator but as a consumer of such
API I might not be aware that I need to.

> Even if we want to make GC observable via finalisation, then it should at
> least be done in a controlled and explicit manner rather than silently
> tacking it onto an unrelated feature. See the revived weakref proposal.

I tend to agree.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>

More information about the es-discuss mailing list