什么是内存泄漏?什么原因会导致呢? |
您所在的位置:网站首页 › 内存为什么会泄露 › 什么是内存泄漏?什么原因会导致呢? |
内存泄露的解释:
程序中己动态分配的堆内存由于某种原因未释放或无法释放。 根据JS的垃圾回收机制,当内存中引用的次数为0的时候内存才会被回收 全局执行上下文中的对象被标记为不再使用才会被释放 内存泄露的几种场景 1、全局变量过多通常是变量未被定义或者胡乱引用了全局变量 // main.js // 场景1 function a(){ b=10; } a(); b++; // 场景2 setTimeout(()=>{ console.log(b) },1000) 2、闭包。未手动解决必包遗留的内存引用。定义了闭包就要消除闭包带来的副作用。 function closuer (){ const b = 0; return (c)=> b + c } const render = closuer(); render(); render = null; // 手动设置为null,GC会自己去清除 3、事件监听未被移除 function addEvent (){ const node = document.getElementById('warp'); node.addEventListener('touchmove',()=>{ console.log('In Move'); }) } const onTouchEnd = (){ const node = document.getElementById('warp'); node. } useEffect(()=>()=>{ const node = document.getElementById('warp'); node.removeEventListener('touchmove'); }) // 类似react 生命周期函数: componentWillUnmount render( |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |