Skip to content
  • Home
  • About
  • No Access
  • Privacy Policy
Bits of .NET
Bits of .NET
  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy
JavaScript

JavaScript: Fix a WeakMap-Based Cache Still Leaking Memory Because the Key Object Is Held Alive by an Unrelated Closure Elsewhere

- 30.10.26 - ErcanOPAK

⚡ Fix a WeakMap-Based Cache Still Leaking Memory Because the Key Object Is Held Alive by an Unrelated Closure Elsewhere

A WeakMap is specifically designed so its entries can be garbage collected the instant nothing else in the program still references the key object – the cache entry itself never keeps the key alive. That guarantee only helps if nothing ELSE is keeping the key alive, though, and a completely unrelated closure – an event listener that captured the object, a setTimeout callback still pending, a second, ordinary cache that happens to also hold a reference – is enough to keep that key reachable indefinitely, in which case the WeakMap entry can never be collected either, not because the WeakMap failed at its job, but because the key was never actually eligible for collection in the first place.

🔎 The Problem

const computedCache = new WeakMap();

function attachHandlers(node) {
  const result = expensiveCompute(node);
  computedCache.set(node, result);          // weak reference, fine on its own

  node.addEventListener('click', () => {
    console.log(node.dataset.id);           // closure captures 'node' directly
  });
  // This listener is never removed, even after 'node' is detached
  // from the document - as long as the listener (or whatever added
  // it) is still referenced, 'node' stays reachable, and so does
  // the WeakMap entry keyed on it.
}

// Profiling heap snapshots months later still shows thousands of
// detached DOM nodes retained, each with a live WeakMap cache
// entry - the WeakMap was never the leak, the listener closures were.

✅ Fix: Find and Release Whatever Else Is Holding the Key

  • Take a heap snapshot in DevTools and use ‘retainers’ on a detached node that should have been collected – this traces the actual reference chain keeping it alive, which is almost always more useful than staring at the WeakMap code itself, since the WeakMap is rarely the culprit.
  • Explicitly remove event listeners (or use an AbortController’s signal to attach them, so a single abort() call detaches everything at once) when a node is removed from the document, rather than assuming garbage collection will clean up listeners on its own.
  • Audit any other cache, registry, or list in the codebase that might also hold a plain (non-weak) reference to the same objects – a single ordinary Map or array alongside the WeakMap is enough to pin every key the WeakMap was supposed to let go of.

🚨 Why This Is Dangerous

  • A WeakMap’s presence in the code can create false confidence that ‘the caching layer can’t be the leak’, which sends debugging effort in the wrong direction while the actual retaining reference – a listener, a timer, a second cache – goes unexamined for far longer than it should.

A WeakMap only releases a key when nothing else is holding onto it – find that other reference, and the WeakMap takes care of itself.

— JavaScript Tip

Related posts:

JavaScript: Use Strict Mode for Better Code

JavaScript: Use Strict Mode for Better Code

JavaScript: Working with JSON Data

JavaScript: Working with JSON Data

JavaScript: Fix Optional Chaining Silently Hiding a Typo in a Property Name Instead of Throwing Wher...

JavaScript: Fix Optional Chaining Silently Hiding a Typo in a Property Name Instead of Throwing Wher...

Views: 7

Post navigation

Git: Fix git rebase -i Reordering Commits Into a State That No Longer Compiles Because an Earlier Commit Secretly Depended on a Later One
Windows 11: Fix the Settings App’s Storage Sense Report Undercounting Temporary Files Because It Only Scans Locations It Has Already Indexed

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

November 2026
M T W T F S S
 1
2345678
9101112131415
16171819202122
23242526272829
30  
« Oct    

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,055)
  • Get the User Name and Domain Name from an Email Address in SQL (981)
  • How to add default value for Entity Framework migrations for DateTime and Bool (977)
  • Get the First and Last Word from a String or Sentence in SQL (858)
  • How to select distinct rows in a datatable in C# (854)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (653)
  • Add Constraint to SQL Table to ensure email contains @ (609)
  • Average of all values in a column that are not zero in SQL (570)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (547)
  • Find numbers with more than two decimal places in SQL (475)

Recent Posts

  • C#: Fix a ConditionalWeakTable Entry Vanishing Too Soon
  • Docker: Fix a Stale COPY Layer After Editing .dockerignore
  • Photoshop: Fix a Pattern Overlay Scaling Wrong on a High-DPI File
  • SQL Server: Fix a Computed Column Index Skipped by Implicit Cast
  • HTML5: Fix a required Input Inside a Hidden Tab Blocking Submit
  • SQL Server: Fix ROW_NUMBER Ties Reordering Between Identical Runs
  • C#: Fix an Enum HasFlag Returning True for the Zero Value
  • WordPress: Fix Featured Images Vanishing After a CDN Migration
  • Photoshop: Fix Content-Aware Fill Smearing a Repeating Pattern
  • Asp.Net Core: Fix Antiforgery Tokens Rejected Behind a Reverse Proxy

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,055)
  • Get the User Name and Domain Name from an Email Address in SQL (981)
  • How to add default value for Entity Framework migrations for DateTime and Bool (977)
  • Get the First and Last Word from a String or Sentence in SQL (858)
  • How to select distinct rows in a datatable in C# (854)

Recent Posts

  • C#: Fix a ConditionalWeakTable Entry Vanishing Too Soon
  • Docker: Fix a Stale COPY Layer After Editing .dockerignore
  • Photoshop: Fix a Pattern Overlay Scaling Wrong on a High-DPI File
  • SQL Server: Fix a Computed Column Index Skipped by Implicit Cast
  • HTML5: Fix a required Input Inside a Hidden Tab Blocking Submit

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com