Back to Blog
JavaScriptWeakRefFinalizationRegistryMemory Management

JavaScript WeakRef and FinalizationRegistry Guide

Master JavaScript WeakRef and FinalizationRegistry for advanced memory management patterns.

B
Bootspring Team
Engineering
July 26, 2019
6 min read

WeakRef and FinalizationRegistry provide advanced memory management capabilities. Here's how to use them responsibly.

Basic WeakRef#

Loading code block...

WeakRef for Caching#

Loading code block...

FinalizationRegistry#

Loading code block...

Resource Cleanup Pattern#

Loading code block...

Unregister Token#

Loading code block...

WeakRef + FinalizationRegistry#

Loading code block...

DOM Element Tracking#

Loading code block...

Event Listener Management#

Loading code block...

Image Cache Example#

Loading code block...

Object Pool with Cleanup#

Loading code block...

Important Caveats#

Loading code block...

Best Practices#

Valid Use Cases: ✓ Caches that can lose entries ✓ Tracking external resources ✓ Secondary cleanup mechanism ✓ Debugging memory leaks Requirements: ✓ Must work if cleanup never happens ✓ Must work if cleanup is delayed ✓ Primary cleanup should be explicit ✓ Finalization is a fallback Performance: ✓ WeakRef.deref() is fast ✓ Don't create many WeakRefs ✓ Clean up dead refs periodically ✓ Avoid in hot paths Avoid: ✗ Critical resource cleanup ✗ Side effects with timing requirements ✗ Assuming GC timing ✗ Complex finalization logic

Conclusion#

WeakRef and FinalizationRegistry enable advanced memory management patterns like weak caches and automatic resource cleanup. WeakRef holds references without preventing garbage collection, while FinalizationRegistry runs callbacks after objects are collected. Always design systems to work correctly without relying on finalization timing, and use these APIs as optimization or fallback mechanisms, not for critical cleanup logic.

Share this article

Help spread the word about Bootspring

Related articles