Yonatan Kra: 0:00 I have an app that adds elements to the DOM and has two buttons. Add Elements, which adds 1,000 elements to the DOM. For each element, it pushes to the elements array. Remove Elements goes over the elements array, and for each element, it removes it from the DOM.
0:21 If I click on Add Elements, I can see it added the elements. If I remove the elements, they are removed. I'll open up the Chrome DevTools in the Memory tab and select Allocation instrumentation on timeline and start recording.
0:39 I'll add elements to the DOM, and I'll remove them. Add some more and remove them as well. Now I'll stop the recording. Let's see what we have. Looking at the blue bars that signify memory allocation that was not garbage collected, we can see that we have a lots of HTML developments and CSS style declarations, which are coming together with the developments. These are the elements that were allocated.
1:10 Looking at one element, we can see that containers of this element, and one of them is our array. We can look that elements array. He's holding our reference to our DOM element. This is the reason it was not cleared from memory. We've found a small leak in our application. We're going to fix it pretty quickly to see how it looks like.
1:36 We'll just set up the length of the elements array to in order to clear it. If now we're going to record again, and we're going to add elements, and move the width three times, maybe even four, so we have four chunks of allocated memory, when we remove the elements, we also remove the elements from the array.
1:59 We can see the grey bars, which signify memory that was allocated but was also garbage collected and removed from memory.
2:09 This solved our small problem of memory leak that just tell the reference to remove the elements. Looking at the grey bar, we see that no element was left in memory after our Remove Elements.