benjamn / benjamn/immutable-tuple

leaks when using primitives; fixable with WeakRef

Open
#8 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
JavaScript
Stars
38
Forks
3
PR merge metrics
No merged PRs in 30d

Description

The description claims "no leaks", but if you do `Tuple(primitive)`, that creates a `UniversalWeakMap` which can never be garbage collected. If you're creating a lot of tuples with a lot of different primitives, that can be a problem.

Now that we have `WeakRef` and `FinalizationRegistry`, I'm pretty sure it's possible to do better, so that there's _actually_ no leaks: that is, no matter how many tuples you create and how you create them, once they've all been GC'd you're guaranteed that no additional memory is held.

The necessary changes are:

1. When `set(key, value)` is called on a `UniversalWeakMap`, store a `WeakRef` to `value` instead of storing `value` directly, and register `value` in a `FinalizationRegistry` so that when it is collected `key` is cleared from the map.
2. Use a global `WeakMap` to store a map from each created tuple to all of its parent nodes.

Then the only strong references to `UniversalWeakMap` objects (except the root) are from the tuples stored in those maps. Once all the tuples stored in a given `UniversalWeakMap` are GC'd, it can be GC'd as well.

The only caveat with this approach is if the user uses a tuple as a key in a weak collection. In that case the tuple can still get collected even if it was only holding primitives, which might be surprising. But that's unavoidable if avoiding leaks.

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.