当前位置:网站首页>JS内存泄漏
JS内存泄漏
2022-06-10 02:51:00 【Float544】
内存泄漏:被分配的内存,既无法使用,又无法被回收。直到浏览器进程结束。
造成的原因:
1.被遗忘的定时器
定时器用完之后 手动关闭 clearInterval() clearTimeout()
2.console.log()
console.log()中接受的对象不会被垃圾回收
3.DOM泄漏
let root = document.querySelector('#root')
let ul = document.querySelector('#ul')
let li3 = document.querySelector('#li3')
// 由于ul变量存在,整个ul及其子元素都不能GC
root.removeChild(ul)
// 虽置空了ul变量,但由于li3变量引用ul的子节点,所以ul元素依然不能被GC
ul = null
// 已无变量引用,此时可以GC
li3 = null
4.意外的全局变量
JS对未声明的变量都会挂载到全局对象上。只有在页面刷新或者关闭时才会释放内存。
使用let const声明变量 或者 使用 严格模式
5.闭包
大多数情况下,闭包会造成内存泄漏。
function fn1(){
let test = new Array(1000).fill('isboyjc')
return function(){
console.log('hahaha')
}
}
let fn1Child = fn1()
fn1Child()
因为返回的函数中没有引用fn1中的变量,所以不存在内存泄漏。
function fn2(){
let test = new Array(1000).fill('isboyjc')
return function(){
console.log(test)
return test
}
}
let fn2Child = fn2()
fn2Child()
这个会造成内存泄漏。因为返回的函数引用了test而test不会被垃圾回收。
解决方法:
1.少使用闭包
2.函数调用后,外部引用置为空 fn2Child = null
边栏推荐
- uniapp 开发app时获取唯一标识OAID,imei,ooid
- Compilation error of GStreamer source code in yocto image construction, causes and Solutions
- 三维重建系统 | L2相机模型
- Li Kou daily question - day 17 -349 Intersection of two data
- electron 打包报错 npm ERR! code ELIFECYCLE npm ERR! errno 1
- Power management (STM32)
- 重磅!DIY的Prometheus主备方案,全网唯一。生产未上,测试先行。
- 获取省市区列表【项目 商城】
- uni-app 移动端本地储存数据库sqlite,无存储限制
- Redis迭代查询详解及其使用:Scan命令、Sscan命令、Hscan命令、Zscan命令
猜你喜欢
MySQL 8.0.29 installation and configuration method graphic tutorial (Windows zip version)

Installation and use of numpy in pycharm

双指针 | 27. 移除元素

Postgresql中如何终止正在执行的查询

Arduino与Processing串口通信(match函数)

Ones Fengbin: from engineer to CTO, with uncertainty and incomplete information | ones talk

Pandas connection database read / write file

86.(leaflet之家)leaflet军事标绘-直线箭头采集

双指针 | 283. 移动零

Double pointer | 27 Removing Elements
随机推荐
Tutorial on using midway
command
Using GDI to realize multi-channel video stream merging
Unity basic operation
ESP32 内部函数/变量无法跳转到定义
2022.05 ESP32 空中升级 OTA
二分法 | 35. 搜索插入位置
从进入内核态看内存管理
2022年PMP考试的3A好考吗?秘籍奉上
MySQL 8.0.28 installation and configuration tutorial
Project practice of data caching using redis
Introduction to 51 single chip microcomputer infrared communication
JDBC入门练习,是版本导致的吗,这错误是什么意思啊?
Sql Server sql语句创建索引
Installation and use of numpy in pycharm
微信小程序 音乐播放代码(播放方式,歌词滚动)
C#/VB. Net to generate directory bookmarks when word is converted to PDF
51单片机入门——步进电机
yocto 构建image出现gstreamer源码编译错误,原因及解决方法
Postgresql中如何终止正在执行的查询