Memory leaks are an annoying and possibly devastating for applications. In frontend Javascript, DOM elements are being added and removed from the DOM but sometimes we forget that elements are referenced inside Javascript. This memory leak is sometimes hard to trace. In this lesson, we see how to compare memory snapshots to track down leaked DOM elements.
Yonatan Kra: [0:00] We have a simple app here that adds elements to the DOM and removes them. We have this Add Elements button. Clicking it adds 1,000 elements to the DOM. Each element it's being pushed into an elements array. We have the Remove Elements, which for each element that was added, it removes it from the DOM.
[0:23] Let's see it in action. I click the Add Element, and 1,000 elements are added. Remove Elements remove them from the DOM. I'll refresh the page and open Chrome DevTools in the Memory tab.
[0:38] I would like to see what happens in memory when adding and removing those elements, so I'll take a snapshot. We see it shows what's in memory. Now I'm going to add the elements, take a snapshot. Comparing these, the before and after, we can see that new HTML elements were added to the DOM, as we expected.
[1:08] Let's remove the elements taking our snapshot. Let's compare this to the first one. We see that even after removal, we still have these HTML elements in the DOM, 1,000 HTML elements, so I would like to get rid of them because we don't need them anymore. They are saved in memory because they are still referenced from this array.
[1:35] A simple way to get rid of them would be to do elements.length = , actually, clear the elements array. If I refresh the page and record, then I add the elements and record, then remove elements and record.
[1:59] If I compare the sixth to the fifth, I'll see that after removing the elements, 1,000 HTML elements...Let's see it deleted. I'll see that 1,000 HTML elements were deleted from memory. This prevents a memory leak when you remove an element from the DOM but keep a reference in JavaScript.