Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

addEventListener memory leaks

When registering an event via addEventListener on an element, then delete that element without removing the event, and doing so repeatedly, would memory be "leaked"?

like image 675
null_radix Avatar asked Apr 13 '10 16:04

null_radix


People also ask

Are memory leaks possible in JavaScript?

If your JavaScript application is experiencing frequent crashes, high latency, and poor performance, one potential cause could be memory leaks.

What is the main cause of memory leaks?

DEFINITION A memory leak is the gradual deterioration of system performance that occurs over time as the result of the fragmentation of a computer's RAM due to poorly designed or programmed applications that fail to free up memory segments when they are no longer needed.

Does setTimeout cause memory leak?

Timers & Events: The use of setTimeout, setInterval, Observers and event listeners can cause memory leaks when heavy object references are kept in their callbacks without proper handling.

Are event listeners garbage collected?

Yes, Event Listeners get garbage collected like all other objects.


2 Answers

It shouldn't leak. The one browser that's infamous for leaking like hell when an event handler causes a host-object<>JS-object loop is IE (up to version 7), and IE (up to version 8) doesn't support addEventListener.

Leave this running and see how the browser's memory usage is affected in the long term, if you want to test it in a particular browser.

<div id="x"></div>
<script type="text/javascript">
    function replace() {
        var x= document.getElementById('x');
        if (x.firstChild!==null)
            x.removeChild(x.firstChild);
        var el= document.createElement('p');
        el.addEventListener('click', click, false);
        x.appendChild(el);
    }
    function click() {
        alert('click');
    };
    setInterval(replace, 1);
</script>

(To test it with a reference loop present, move the function click definition up into the replace body.)

like image 169
bobince Avatar answered Sep 20 '22 00:09

bobince


You will get memory leak if you delete from DOM, elements that have attached listeners. But this only occurs in IE, Fx and others have advanced GC.

Often it happens, if you manipulate with DOM elements not via DOM, but like

el.innerHTML = ...

For example, YUI has custom realization setInnerHTML, to prevent memory leak in this case.

like image 45
Alex Ivasyuv Avatar answered Sep 21 '22 00:09

Alex Ivasyuv