【问题标题】:Js ArrayBuffer memory leakJs ArrayBuffer 内存泄漏
【发布时间】:2022-07-06 21:51:00
【问题描述】:

我对 ArrayBuffer 有疑问。我不明白为什么内存没有释放。也许有人知道如何解决它。

Code in github

Video in youtube

  // Main thread
  const startLongTask = () => {
    setLoading(true);

    const worker = new Worker(
      new URL("../webworkers/matrix.js", import.meta.url)
    );

    worker.onmessage = ({ data }) => {
      setLoading(false);
      console.log(data);

      worker.terminate();
    };

    const matrix = new Uint8Array(1000000000);
    worker.postMessage(matrix, [matrix.buffer]);
  };
// Worker thread
onmessage = ({ data: matrix }) => {
  const matrixView = new DataView(matrix.buffer);
  for (let i = 0; i < matrix.byteLength; i++) {
    matrixView.setInt8(i, i >= 255 ? 255 : i);
  }
  postMessage(matrix, [matrix.buffer]);
};

【问题讨论】:

标签: javascript web-worker arraybuffer


【解决方案1】:

由于console.log(data);,似乎存在内存泄漏

使用 console.log

https://monosnap.com/file/Qwbu7LRGWFaHptic1bG5YLsVGyKj7d

没有 console.log

https://monosnap.com/file/3yrkGDeCQo1jWxQ10SSDUDFXvd9g8T

【讨论】:

  • Thaks,但是 firefox 做同样的事情,在 linux 和 mac 上测试过。 Mac Safari 可以处理有和没有 console.log 的两种情况,但速度很慢。第二次点击后的Iphone safari和chrome进入无限循环,第二次点击后firefox崩溃。
  • vanila js 的结果相同。
【解决方案2】:

console.log() 存储对象的引用,因此它不能被垃圾收集。即使在您的函数完成后,该对象仍驻留在控制台中。

https://javascript.plainenglish.io/these-5-bad-javascript-practices-will-lead-to-memory-leaks-and-break-your-program-9cf692303043

控制台打印是否也会导致内存泄漏?是的,如果浏览器并不总是存储我们打印的对象的信息,那为什么每次打开控制台都能看到具体的数据呢?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-18
    • 1970-01-01
    • 1970-01-01
    • 2013-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多