Search code examples
javascriptweb-worker

Allowable format for webworker data transfer


I've been looking at how to transfer data to and from webworkers, and every example I've found has shown the following format:

var myData = new Uint8ClampedArray(256);
postMessage(myData.buffer, [ myData.buffer ]);

However I'd like to be able to send additional data. So, my question is does the following also transfer ownership of myData's buffer, or is it just copying?

var myData = new Uint8ClampedArray(256);
postMessage({ foo: 'bar', data: myData }, [ myData.buffer ]);

Solution

  • I just returned to this after a couple months, and decided to run a benchmark. Unfortunately I couldn't figure out how to do it properly on jsperf, so I went ahead and put this gist together. Using a 1 MB Uint8ClampedArray over 10000 round-trip loops, my results were as follows:

    worker.postMessage(data, [ data.buffer ]);
    // => 1112ms
    
    worker.postMessage({ foo: 'bar', data: data }, [ data.buffer ]);
    // => 1220ms
    
    worker.postMessage(data);
    // => 11862ms
    
    worker.postMessage({ foo: 'bar', data: data });
    // => 12244ms
    

    The results were basically what I expected, but it's nice to have confirmation. There does appear to be some overhead (~10%) with adding extra data in an object, but array buffer ownership is transferred properly.