why?
解决办法参考:http://www.ibm.com/developerworks/library/wa-memleak/index.html
交互越来越复杂,功能越来越多,可能出现分配的内存,不能及时回收,导致memory leak。结果就会浏览器越来越慢,甚至崩溃
how?
Remember to check and nullify variables that contain references to DOM elements which may be getting updated/destroyed during the lifecycle of your app.
what?
低级语言,比如c,通过malloc() 和free(),人工实现内存分配和回收。但js中,都是浏览器实现内存管理。那么浏览器是怎么实现内存回收的呢?
从2008年起,高级浏览器都是采用mark-and-sweep的方式,实现垃圾回收。简单的说,就是定时查看一个object,是否可以通过root(比如window)引用上。如果不能,那么就会删除。(同时还包含闭包规则,内部的可以方位外部环境的object)
看看几种常见的导致内存泄露的问题
情况1
01 | function Menu(title) { |
02 | this .title = title |
03 | this .elem = document.getElementById( 'id' ) |
04 | } |
06 | var menu = new Menu( 'My Menu' ) |
07 |
08 | document.body.innerHTML = '' // (1) |
Here we have the memory structure:
dom元素不存在了,但是在内存中依然有引用。
可以加上 menu = null ,这样,mark-and-sweep机制就会把内存中的变量删除
情况2
大量的没有即使删除的事件处理函数
function LeakMemory(){
for(i = 0; i < 8000; i++){
var parentDiv = document.createElement("div");
parentDiv.innerHTML = "<div onClick='foo()'></div>";
}
}
情况3闭包导致的memory leak
Closures often lead to circular references. For example:
function setHandler() {
var elem = document.getElementById('id')
elem.onclick = function() {
// ...
}
}
var elem = document.getElementById('id')
elem.onclick = function() {
// ...
}
}
Here, the DOM element references the function directly via onclick
. And the function references elem
through the outer LexicalEnvironment
.
This memory structure appears even if the handler has no code inside. Special methods like addEventListener/attachEvent
also create the reference internally.
onclick函数中,可以访问到elem,说以elem 不会被回收
解决办法参考:http://www.ibm.com/developerworks/library/wa-memleak/index.html
http://javascript.info/tutorial/memory-leaks
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory_Management