Removing DOM nodes with proper GC (no leaks)

守給你的承諾、 提交于 2019-12-08 19:04:22

问题


The problem

Adding nodes, while removing the old ones from the DOM, doesn't discard the old nodes from memory. (not all of them at least, without apparent reason).

How to see this happening

(you already know this but anyway..)
right click the output area and inspect using Chrome developer tools. Click on the Timeline tab and then at the circle (dot) on the upper left side to start recording.

now click on the body element, and it will start adding and removing items every 300ms
(the removed nodes should be garbage collected).

Stop the recording, extend the data-sampling zone to maximum, and you will see on the bottom half of the screen, in green, the nodes. the expected graph would be going up and down (where down means nodes have been discarded properly by the GC).

Test pages

These 2 test pages are very primitive. of course in real life developers use templates which generates huge amount of text which should be converted into DOM and injected into the page, therefor the number of live DOM nodes in memory should be kept low, and removed ones must be discarded.

with jQuery - http://jsbin.com/lamigucuqogi/2/edit - After about 40 seconds the GC is getting crazy and stops collecting removed nodes, which causes inflation.

Naive way - http://jsbin.com/riref/2/edit - Also it seems nodes aren't being removed in a satisfying rate, and the number keeps growing and growing...

Question

Why is this happening, and how should one properly remove NODES so inflation won't occur?


回答1:


You are mistaken. If you leave the example running for a significant period of time, then use the garbage can icon in the Dev Tools timeline to force a garbage collection you will observe that the nodes are freed.

Like any other JavaScript object, DOM nodes become eligible for GC when they become unreachable from GC Roots. Provided you do not retain any other references to removed nodes (in an array, for example), they become unreachable once removed from the main document.

However, they are not garbage collected immediately - a GC run can take time, during which the main browser thread is blocked, so it only runs periodically. What you are seeing is a period during which the JavaScript engine has decided not to run the garbage collector. You shouldn't be concerned by this - your code does allow the garbage collector to free memory when it eventually runs.

Highly recommended viewing - Addy Osmani's memory management masterclass.



来源:https://stackoverflow.com/questions/26239205/removing-dom-nodes-with-proper-gc-no-leaks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!