1

I have a problem with ArrayBuffer. I don't understand why memory not frees up. Maybe someone knows how to fix it.

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]);
};
  • Does this answer your question? [Memory leak when logging complex objects](https://stackoverflow.com/questions/12996129/memory-leak-when-logging-complex-objects) – tevemadar Jun 01 '22 at 20:08

2 Answers2

1

It looks like there is memory leak because of console.log(data);

With console.log

https://monosnap.com/file/Qwbu7LRGWFaHptic1bG5YLsVGyKj7d

Without console.log

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

Sergey
  • 316
  • 1
  • 4
  • Thaks, but firefox do the same thing, tested on linux and mac. Mac safari handle both scenarios with and without console.log, but very slow. Iphone safari and chrome after second click goes to infinite loop, firefox after second click crash. – Tadas Bružas Jun 01 '22 at 22:18
  • Same result in vanila js. – Tadas Bružas Jun 01 '22 at 23:03
0

console.log() stores a ref to the object, and hence it can't be garbage collected. The object still resides in the console, even after your function finishes.

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

Does console printing also cause a memory leak? Yes, if the browser doesn’t always store information about the object we print, how come we can see the specific data every time we open the Console?

Cory
  • 1
  • 1