swiftwasm/JavaScriptKit

Use FinalizationRegistry to auto-deinit Closures

nmn opened this issue · 3 comments

nmn commented

There is a new-ish JS API called FinalizationRegistry that lets you add a finalization callback to values in Javascript that gets run sometime after a value is Garbage Collected in Javascript.

Together with WeakRef, this API could be used to automatically release/deinit JSClosures which currently need to managed manually.

Here's an article describing it's use within JS: https://v8.dev/features/weak-references
Another article describing it's use for Wasm/Wasi: https://rob-blackbourn.github.io/blog/webassembly/wasm/wasi/javascript/c/clang/wasi-sdk/marshalling/finalizer/finalizationregistry/2020/07/07/wasi-finalizers-1.html

There is probably some cost associated with using this API, so I don't think that all JSClosures should have this behaviour. Frameworks such as Tokamak can probably handle event listeners just fine, but in other cases it would make things much easier.

The feature is supported in all modern browsers (including Safari 14.1 +)

@j-f1 has a PR to implement this I believe at #128

j-f1 commented

Ooh interesting idea: I could restore the old closure behavior as JSUnmanagedClosure, with the plain JSClosure throwing if it’s unsupported.

j-f1 commented

Implemented in #128