Search code examples
javascriptmultidimensional-arrayweb-workertransferable

Is there a way to pass an array of objects to a web worker as a transferable object?


I'm working on a CPU and memory intensive project for which some of the processing is sent to a web worker in order to not hang the browser while its number crunching. The problem I am facing is that I need to send to the web worker instance a few multidimensional arrays, but upon profiling the app I realized it was cloning the arrays, so I'l trying to see if I pass them as transferable objects.

For simplicity assume that the arrays I'm trying to pass are:

var myArray1 = [{a: 0, b: "0"}, {a: 1, b: "0"}];

var myArray2 = [{c: 0, d: "0"}, {c: 1, d: "0"}];

Is there a way to pass these as transferable objects to a web worker instance?


Solution

  • Not directly but ArrayBuffers and SharedArrayBuffers can be transferred to web workers and if your data is as uniform as in your example then it would be possible to store that data in an array buffer rather than an array of objects.

    Instead of

    const arr = [{ a: 0, b: '0' }];
    

    you might store the data as

    const ab = new ArrayBuffer(2 * 4);
    const dv = new DataView(ab);
    dv.setFloat32(0, 0);
    dv.setUint32(4, '0'.charCodeAt(0));
    

    And then read it back using a data view in the worker, as well. This will let you transfer the data to the worker using a transferable item. Of course this all depends on your data and how it's structured.