0

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?

Evan
  • 25
  • 5
  • 1
    No, only [typed arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) can be transferable objects. – Patrick Roberts Dec 20 '18 at 23:42

1 Answers1

0

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.

Garrett Johnson
  • 2,413
  • 9
  • 17
  • As I had to move along with this project, for the time being I simply capped the size of the workload that will be allowed to be passed to the web worker and added a failover fork for all other cases (including for browsers that don't support web workers). This said, I'll take a look if your suggested approach would work a bit later, given that the data structure is by far more complicated than my simplified example. Thanks for the suggestion Garrett – Evan Jan 02 '19 at 22:52