CodePark/ questions / Memory leaks in SPAs
START PRACTICINGPRACTICE
Frontend question · Browser & web performance › Memory leaks in SPAs

You want to store extra data for DOM elements, like a tooltip's settings, without keeping removed elements in memory. Which store should you use?

A WeakMap with the element as the key

A WeakMap holds its keys weakly. When nothing else references the element, the garbage collector can free it, and its entry disappears too.

"A
Map with the element as the key" is the tempting wrong answer. A Map holds a strong reference to every key. So removed elements stay in memory until you delete them by hand. The array has the same problem. The object keyed by id doesn't keep the element alive, but its data stays forever unless you clean it up.