I'm resurrecting this [1] because I have found a use case where I needed a
weak reference. Is there any chance this could get into the language?

Here's my particular use case: making a stream with a rotating destination
that itself acts as a stream (snippet of that code, or what I'd like it to
be).

```js
function rotateStream(interval, format) {
    // Without the weak reference here, there's a memory leak
    const ref = new WeakReference({})
    setStream(ref.get(), format)
    setInterval(function () {
        if (ref.exists()) setStream(ref.get(), format)
        else clearInterval(this)
    }, interval)
    return ref.get()
}
```

This basically rotates an active stream, with the weak reference pointing
to the said stream. The alternative requires explicit marking (in this
case, with a `close` method):

```js
function leakyRotateStream(interval, format) {
    let stream = {close() {
        clearInterval(timer)
        timer = stream = null
    }}
    const timer = setInterval(function () {
        setStream(stream, format)
    }, interval)
    setStream(stream, format)
    return stream
}
```

In this use case, weak references would simplify the implementation and
reduce memory costs. And I would rather take advantage of the GC machinery
than explicit memory management (as explicit as C), as it would be easier
to collect when that's the only thing referenced.

(The setInterval callback is gc'd with all its references when it's cleared
from within.)

Thankfully, I'm using Node.js, so `weak` [2] is an option (the only option,
really). But I would definitely appreciate if it was available in JS
proper, across engines. V8, SpiderMonkey, and JSC all have weak references
to JS objects as part of their public API, and I would be surprised if the
implementation work would be anything significant.

[1]: https://esdiscuss.org/topic/what-is-the-status-of-weak-references
[2]: https://github.com/TooTallNate/node-weak

-- 
Isiah Meadows
_______________________________________________
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss

Reply via email to