nexttick

JavaScript performance comparison

Revision 2 of this test case created

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var nextTick1 = function () {
      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 = 'data:,foo';
      }
      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;
    }();
   
};
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
setTimeout
// async test
nextTick2(function() {
  deferred.resolve();
});
pending…
setTimeout
// async test
nextTick2(function() {
  deferred.resolve();
});
pending…
Image.onerror
// async test
nextTick3(function() {
  deferred.resolve();
});
pending…
script.onload
// async test
nextTick4(function() {
  deferred.resolve();
});
pending…
XMLHttpRequest.onreadystatechange
// async test
nextTick5(function() {
  deferred.resolve();
});
pending…
window.onmessage
// async test
nextTick6(function() {
  deferred.resolve();
});
pending…
requestAnimationFrame
nextTick7(function() {
  deferred.resolve();
});
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:

0 comments

Add a comment