postMessage
JavaScript performance comparison
Info
echoSetTimeout is used when features aren't available. For instance: - No workers (IE6-9, 10?) - No MessageChannel (FF<=4)
Preparation code
<script>
var payload = {
shortString: 'test',
simple: {
foo: "bar",
arr: []
}
};
var echoSetTimeout = (function() {
return function(msg, cb) {
setTimeout(cb, 0);
}
})();
var echoWorker = (function() {
var code = 'onmessage = function(e) { postMessage(e.data) };';
var blobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder;
if(!blobBuilder) {
return echoSetTimeout;
}
var bb = new (blobBuilder)();
bb.append(code);
var blobURL = (window.URL || window.webkitURL || window.mozURL).createObjectURL(bb.getBlob());
var worker = new Worker(blobURL);
return function(msg, cb) {
worker.onmessage = cb;
worker.postMessage(msg);
};
})();
var echoIFramePostMessage = (function() {
var iframe = document.createElement('iframe');
window.onload = function() {
iframe.style.display = 'none';
document.body.appendChild(iframe);
iframe.contentDocument.write('<html><head><script>onmessage = function(e) { e.source.postMessage(e.data, "*") };<'+'/script><'+'/head><'+'/html>');
};
return function(msg, cb) {
window.onmessage = cb;
iframe.contentWindow.postMessage(msg, '*');
};
})();
var echoPostMessage = (function() {
return function(msg, cb) {
async = false;
window.onmessage = cb;
window.postMessage(msg, '*');
async = true;
};
})();
var echoMessageChannel = (function() {
if(!window.MessageChannel)
return echoSetTimeout;
var mc = new MessageChannel();
return function(msg, cb){
mc.port1.onmessage = cb;
mc.port2.postMessage(msg);
};
})();
</script>
Test runner
Warning! For accurate results, please disable Firebug before running the tests. (Why?)
Java applet disabled.
| Test | Ops/sec | |
|---|---|---|
Worker shortString |
|
pending… |
sameWindowPostmessage shortString |
|
pending… |
setTimeout shortString |
|
pending… |
MessageChannel shortString` |
|
pending… |
iframe shortString |
|
pending… |
Compare results of other browsers
Revisions
You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:
- Revision 1: published by Malte Ubl
- Revision 2: published
- Revision 3: published by David Bruant
1 comment
Degrading down to setTimeout is really annoying, as it's hard to compare browsers. It's better to fail than to degrade in a performance test like this.