基本概念
内存溢出(out of memory):是指程序在申请内存时,没有足够的内存空间供其使用,就会出现out of memory,内存溢出。
内存泄露(memory leak):是指程序在申请内存后,无法释放已申请的内存空间。
内存泄露最终会导致内存泄露。
console.log导致的内存泄露
console.log打印也会造成内存泄露
html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>test</title>
<style>
body{
margin:0;
}
#app{
height: 100vh;
}
</style>
</head>
<body>
<div id='app' onclick="test()"></div>
<script>
function test(){
let arr = new Array(10000).fill(0)
// 使用console.log
console.log(arr)
// 不使用console.log
// return arr
}
</script>
</body>
</html>使用了console.log的JS堆变化

未使用console.log的JS堆变化

前端中定位和分析内存泄露的方法
Chrome Dev Tools的性能(performance)Tab:可以查看JS堆和节点等信息随时间的变化 Chrome Dev Tools的内存(memory)Tab:可以查看实时的JS堆总大小和拍摄堆快照
前端中解决内存泄露的方法
- 用完变量之后,将变量重新赋值为null或者undefined;
- 使用ES6 WeakSet/WeakMap