Skip to content

Instantly share code, notes, and snippets.

@usefulthink
Created March 1, 2016 23:30
Show Gist options
  • Save usefulthink/162298f3b678063c2914 to your computer and use it in GitHub Desktop.
Save usefulthink/162298f3b678063c2914 to your computer and use it in GitHub Desktop.
short test to compare performance of transfers vs regular value-passing to and from workers
function createWorker(mainFn) {
var blob = new Blob(['(' + mainFn.toString() + ')()']);
var blobURL = window.URL.createObjectURL(blob);
return new Worker(blobURL);
}
var typedArray = new Float32Array(100000);
var plainArray = [];
// create two big arrays with random numbers
for (var i=0; i<typedArray.length; i++) {
var v = Math.random();
plainArray[i] = v;
typedArray[i] = v;
}
// create a worker that simple doubles all values in the
// data-array passed
function getWorker() {
return createWorker(function() {
self.onmessage = function(ev) {
console.time('in worker');
var data = ev.data;
for (var i=0; i<data.length; i++) {
data[i] = 2 * data[i];
}
console.timeEnd('in worker');
self.postMessage(data, data.buffer ? [data.buffer] : null);
}
});
}
function runPlainArrayTest() {
console.log('--- runPlainArrayTest');
var worker = getWorker();
return new Promise(resolve => {
console.time('plainArray');
worker.postMessage(plainArray);
worker.onmessage = function() {
console.timeEnd('plainArray');
worker.terminate();
resolve();
};
});
}
function runTypedArrayTest() {
console.log('--- runTypedArrayTest');
var worker = getWorker();
return new Promise(resolve => {
console.time('typedArray');
worker.postMessage(typedArray, [typedArray.buffer]);
worker.onmessage = function() {
console.timeEnd('typedArray');
worker.terminate();
resolve();
};
});
}
function runConvertToTypedArrayTest() {
console.log('--- runConvertToTypedArrayTest');
var worker = getWorker();
return new Promise(resolve => {
console.time('convertedTypedArray');
var tmpTypedArray = new Float32Array(plainArray);
worker.postMessage(tmpTypedArray, [tmpTypedArray.buffer]);
worker.onmessage = function() {
console.timeEnd('convertedTypedArray');
worker.terminate();
resolve();
};
});
}
runPlainArrayTest()
.then(runTypedArrayTest)
.then(runConvertToTypedArrayTest);
@usefulthink
Copy link
Author

These are the results on my machine (you can just run it in chrome's console yourself).

--- runPlainArrayTest
in worker: 26.739ms
plainArray: 157.424ms

--- runTypedArrayTest
in worker: 1.761ms
typedArray: 33.730ms

--- runConvertToTypedArrayTest
in worker: 2.153ms
convertedTypedArray: 54.992ms

so not only is the transfer significantly faster (even if we create the typed array first), also the processing has an incredible performance gain from using typed-arrays (i'd suspect this is due to reduced cost of value-access).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment