javascript, circular references and memory leaks

后端 未结 3 1591
长情又很酷
长情又很酷 2020-12-04 20:01

From what I recall of a not too distant past, Javascript interpreters suffered from memory leaking issues when faced with circular references.

Is it still the case i

3条回答
  •  旧时难觅i
    2020-12-04 20:43

    To add to bobince answer, I did some tests with IE8.

    I tried almost all examples provided at http://www.javascriptkit.com/javatutors/closuresleak/index.shtml

    No one of them is leaking memory anymore (at least not in a perceivable way), except the example that removes child nodes with events still attached to them.

    This type of example I think it's better explained by Douglas Crockford in his queuetest2.

    This one still leaks memory on IE8 and it's pretty easy to test by simply running the test script and looking at Windows Task Manager - Performance - PF Usage. You will see PF Usage increases by almost 1MB per loop (very fast).

    But in IE8 the memory is released on page unload (like navigating to a new page or reloading the same page) and obviously also when totally closing the browser.

    So in order for a final user to perceive this memory leaks on IE8 (as reduced systerm performances), he needs to stay on the same page for a long time, which in now days it can frequently happen with AJAX, but this page need also to do hundreds of childnodes removal of elements with event attached to them.

    Douglas Crockford test is stressing the browser with 10000 nodes added and then removed, that's excellent for showing you the issue, but in real life I never had a page that removed more than 10 elements. INMHO usually it's faster to use display: none rather than removing an entire set of nodes, that's why I don't use removeChild that much.


    For whoever might be more interested in the IE8 memory leak explained above, I did another test and it seems mem leaks do not show up at all in IE8 when using innerHTML in place of appendChild/removeChild to add/remove child elements with attached events. So apparently Douglas Crockford purge function (suggested by him to prevent memory leaks in IE) is not necessary anymore in IE8 at least when using innerHTML...

    (EDITED thanks to 4esn0k comment below) ...moreover Douglas Crockford purge function does NOT work at all on IE8, in his code var a = d.attributes returns NO onclick attributes (or any other onevent attributes) that were added at runtime on IE8 (they do are returned on IE7).

    Douglas Crockford says:

    "The purge function should be called before removing any element, either by the removeChild method, or by setting the innerHTML property."

    I provide here the code for the test:

        
       

    queuetest2 similar to the one provided by Douglas Crockford at http://www.crockford.com/javascript/memory/leak.html
    but this one adds/removes spans using innerHTML instead of appendChild/removeChild.

提交回复
热议问题