nexttick
JavaScript performance comparison
Preparation code
<script>
Benchmark.prototype.setup = function() {
var nextTick1 = function () {
// Firefox doesn't support MessageChannel so we use something that works..
if (!('MessageChannel' in window)) {
return function(fn) { setTimeout(fn, 0) }
}
var channel = new MessageChannel();
var queue = [];
channel.port1.onmessage = function () {
queue.shift()();
};
function nextTick(fn) {
queue.push(fn);
channel.port2.postMessage();
}
return nextTick;
}();
var nextTick2 = function () {
function nextTick(fn) {
return setTimeout(fn, 0);
}
return nextTick;
}();
var nextTick3 = function () {
function nextTick(fn) {
var image = new Image();
image.onerror = fn;
image.src = '///';
}
return nextTick;
}();
var nextTick4 = function () {
function nextTick(fn) {
var script = document.createElement('script');
script.onload = function() {
document.body.removeChild(script);
fn();
}
script.src = 'data:text/javascript,';
document.body.appendChild(script);
}
return nextTick;
}();
var nextTick5 = function () {
// FAILS ON SOME BROWSERS SO USE SETTIMEOUT INSTEAD
function nextTick(fn) {
var req = new XMLHttpRequest;
req.open('GET','data:text/plain,foo', false);
req.onreadystatechange = function() {
req.onreadystatechange = null;
fn();
};
req.send(null);
}
return nextTick;
}();
var nextTick6 = function () {
var key = 'nextTick__' + Math.random();
var queue = [];
window.addEventListener('message', function (e) {
if (e.data !== key) {
return;
}
queue.shift()();
},false);
function nextTick(fn) {
queue.push(fn);
window.postMessage(key, '*');
}
return nextTick;
}();
var nextTick7 = function () {
function nextTick(fn) {
requestAnimationFrame(fn);
}
return nextTick;
}();
var nextTick8 = function () {
var resolved = Promise.resolve();
function nextTick(fn) {
resolved.then(fn);
}
return nextTick;
}();
};
</script>
Test runner
Warning! For accurate results, please disable Firebug before running the tests. (Why?)
Java applet disabled.
Test | Ops/sec | |
---|---|---|
Promise.prototype.then
|
|
pending… |
window.onmessage
|
|
pending… |
requestAnimationFrame
|
|
pending… |
MessageChannel (fallback to setTimeout on Firefox)
|
|
pending… |
setTimeout
|
|
pending… |
Image.onerror
|
|
pending… |
script.onload
|
|
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.
- Revision 1: published
- Revision 2: published
- Revision 3: published
- Revision 4: published
- Revision 5: published Manuel Astudillo
- Revision 6: published
- Revision 7: published
- Revision 8: published Miller Medeiros
- Revision 10: published S Jobs
- Revision 11: published evan
- Revision 12: published
- Revision 13: published
- Revision 14: published
- Revision 15: published dfgdsdfsfdsdfgq
- Revision 16: published dfgdsdfsfdsdfgq
- Revision 17: published dfgdsdfsfdsdfgq
- Revision 23: published
0 Comments