Reuse two buffers between a page and a worker without copying
Moving decoded images, audio buffers, or ML weights between workers. Ping-ponging a fixed pool of reusable buffers between two threads to avoid GC churn.
A worker needs somewhere to put each result, and making a fresh 8 MB buffer every time is wasteful. This page makes two, once. One goes to the worker, which fills it and sends it back, while the other is being read here. Then they swap. The counters show megabytes moved climbing and megabytes copied staying at zero.
Code
const pool = [new ArrayBuffer(SIZE), new ArrayBuffer(SIZE)];
worker.onmessage = ({ data }) => {
use(data.buffer); // read the result
worker.postMessage({ buffer: data.buffer }, [data.buffer]); // and send the same memory back
};
for (const buffer of pool) worker.postMessage({ buffer }, [buffer]);
Step by step
What each press of Next does in this demo.
- Start the pool. Two buffers are made once, and then only moved.
- Stop. The pool stops. Two buffers were ever made.