3. wait! what is a memory leak? "When a system does not correctly manage its memory allocations, it is said to leak memory. A memory leak is a bug . Symptoms can include reduced performance and failure. " -- Douglas Crockford
11. let‘s code a memory leak! // This will approx add 1 MB of memory if executed 1000 times // …each reload! var el = document.createElement("div"); var fnOver = function(e) { el.innerHTML = "Mouse over!"; }; el.onmouseover = fnOver; document.getElementsByTagName("body")[0].appendChild(el); // Removes the element, but it‘s still in the memory el.parentNode.removeChild(el);
12. where‘s the … uhm … circular whatever?! // This will approx add 1 MB of memory if executed 1000 times // …each reload! var el = document.createElement("div"); var fnOver = function(e) { el.innerHTML = "Mouse over!"; }; el.onmouseover = fnOver; document.getElementsByTagName("body")[0].appendChild(el); // Removes the element, but it‘s still in the memory el.parentNode.removeChild(el);
13. ah, there it is! // This will approx add 1 MB of memory if executed 1000 times // …each reload! var el = document.createElement("div"); var fnOver = function(e) { el .innerHTML = "Mouse over!"; }; el .onmouseover = fnOver ; document.getElementsByTagName("body")[0].appendChild(el); // Removes the element, but it‘s still in the memory el.parentNode.removeChild(el);
14. explanation " Memory leaks related to event handlers are, generally speaking, related to enclosures. In other words, attaching a function to an event handler which points back to its element can prevent browsers from garbage-collecting either. " -- Some guy in some forum
15. explanation " Memory leaks related to event handlers are, generally speaking, related to enclosures. In other words, attaching a function to an event handler which points back to its element can prevent browsers from garbage-collecting either. " -- Some guy in some forum Circular Reference!
18. the "purger" function purge(d) { var a = d.attributes, i, l, n; if (a) { for (i=0, l=a.length; i<l; i++) { n = a[i].name; if (typeof d[n] === 'function') { d[n] = null; } } } a = d.childNodes; if (a) { for (i=0, l=a.length; i<l; i++) { purge(d.childNodes[i]); } } }
19. what does it do? "The purge function takes a reference to a DOM element as an argument. It loops through the element's attributes. If it finds any functions, it nulls them out. This breaks the cycle, allowing memory to be reclaimed . It will also look at all of the element's descendent elements, and clear out all of their cycles as well " -- http://javascript.crockford.com/memory/leak.html
20. our memory leak: fixed. var el = document.createElement("div"); var fnOver = function(e) { el.innerHTML = "Mouse over!"; }; el.onmouseover = fnOver; document.getElementsByTagName("body")[0].appendChild(el); // Run our garbage collector purge(el); // Removes the element el.parentNode.removeChild(el);