Skip to content

Instantly share code, notes, and snippets.

@grind086
Created April 16, 2017 20:43
Show Gist options
  • Save grind086/47cd2bb5c8a3ff5877962a88a774dbd3 to your computer and use it in GitHub Desktop.
Save grind086/47cd2bb5c8a3ff5877962a88a774dbd3 to your computer and use it in GitHub Desktop.
Testing ownership transfer on WebWorkers
<html>
<head>
<script type='javascript/worker' id='bufferWorker'>
self.onmessage = function(e) {
var data = e.data;
self.postMessage(data, [ data.buffer ]);
}
</script>
<script type='javascript/worker' id='objectWorker'>
self.onmessage = function(e) {
var data = e.data;
self.postMessage(data, [ data.data.buffer ]);
}
</script>
<script type='javascript/worker' id='echoWorker'>
self.onmessage = function(e) {
var data = e.data;
self.postMessage(data);
}
</script>
<script type='text/javascript'>
var dataSize = 1024 * 1024;
var loopCount = 10000;
function workerFromId(id) {
var source = document.querySelector('#' + id).textContent;
var blob = new Blob([source], { type: 'text/javascript' });
return new Worker(window.URL.createObjectURL(blob));
}
function runTest(worker, fn) {
return new Promise((res, rej) => {
var now, data;
var cumTime = 0;
var i = 0;
function iter() {
if (now) {
cumTime += Date.now() - now;
}
if (i++ >= loopCount) {
return res(cumTime);
}
data = new Uint8ClampedArray(dataSize);
now = Date.now();
fn(worker, data, iter);
}
iter();
});
}
var bufferWorker = workerFromId('bufferWorker');
var objectWorker = workerFromId('objectWorker');
var echoWorker = workerFromId('echoWorker');
var bufferTime;
var objectTime;
var echoBufferTime;
var echoObjectTime;
Promise.resolve()
.then(() => {
return runTest(bufferWorker, (worker, data, done) => {
worker.onmessage = done;
worker.postMessage(data, [ data.buffer ]);
}).then((t) => bufferTime = t);
})
.then(() => {
return runTest(objectWorker, (worker, data, done) => {
worker.onmessage = done;
worker.postMessage({ foo: 'bar', data: data }, [ data.buffer ]);
}).then((t) => objectTime = t);
})
.then(() => {
return runTest(echoWorker, (worker, data, done) => {
worker.onmessage = done;
worker.postMessage(data);
}).then((t) => echoBufferTime = t);
})
.then(() => {
return runTest(echoWorker, (worker, data, done) => {
worker.onmessage = done;
worker.postMessage({ foo: 'bar', data: data });
}).then((t) => echoObjectTime = t);
})
.then(() => {
console.log([
`Buffer: ${bufferTime}`,
`Object: ${objectTime}`,
`Echo Buffer: ${echoBufferTime}`,
`Echo Object: ${echoObjectTime}`
].join('\n'));
});
</script>
</head>
<body>
</body>
</html>
@grind086
Copy link
Author

Results:

Buffer: 1112
Object: 1220
Echo Buffer: 11862
Echo Object: 12244

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