js memory leak

why?

交互越来越复杂,功能越来越多,可能出现分配的内存,不能及时回收,导致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

01function Menu(title) {
02  this.title = title
03  this.elem = document.getElementById('id')
04}
06var menu = new Menu('My Menu')
07 
08document.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() {
    // ...
  }

}

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




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值