js中常见内存泄漏和场景

内存泄漏常见情形

image

为了排查chrome插件对内存占用的干扰,最好再隐身模式下调试代码;
谷歌浏览器对内存的调试有两个可用面板:性能(Merformance)+ 内存(Memory)
一般先在性能(Merformance)面板录制内存占用随时间变化的图像,对是否存在内存泄漏有个直观的判断;然后在内存(Memory)面板定位问题发生的位置;

1. 使用过多的全局变量

代码示例:

<!DOCTYPE html>
<html>

<head>
  <title>
    Memory Profile
  </title>
</head>

<body>
  <button onclick="grow()">Global Var</button>
  <script type="text/javascript">

    function LargeObj() {
      this.largeArr = new Array(1000000);
    }

    var x = [];

    function grow() {
      var o = new LargeObj();

      x.push(o);
    }
  </script>
</body>

</html>

排查调试:

(1)看内存变化情况
image
(2)执行可疑操作,前后怕快照,查看
image
image
(3) 定位内存分配在代码中的位置
蓝色条、灰色条可以看到内存分配和回收的时机和频率
image

2. 存在分离的dom

分离的dom是指dom从dom树中移除了,但是代码js中存在对它的引用

代码示例:

<!DOCTYPE html>
<html>

<head>
  <title>
    Memory Profile
  </title>
</head>

<body>
  <button id="button">移除列表</button>
  <ul id="list">
    <li>项目 1</li>
  </ul>
  <script type="text/javascript">
    var button = document.getElementById('button');
    var list = document.getElementById('list');

    button.addEventListener('click', function () {
      list.remove();
    });
  </script>
</body>

</html>

排查调试:

image
image

3. 闭包造成的内存泄漏

代码示例:

image

排查调试:

image

4. 控制台打印等、打印不当造成内存泄漏

(生产建议去掉打印语句)

推荐视频:https://www.bilibili.com/video/BV13y4y1H71m/?spm_id_from=333.337.search-card.all.click&vd_source=24e9533d85b0805ca09a73b03223aee4

注明:本文是对视频的总结

posted @ 2026-08-18 14:49  ฅ˙-˙ฅ  阅读(4)  评论(0)    收藏  举报