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]);
};
1

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

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.
Same result in vanila js.
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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.