setTimeout vs nextTick polyfill

JavaScript performance comparison

Revision 2 of this test case created by Scott

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    window.nextTick = (function(global) {
      var msgName = 'nextTick-polyfill',
        timeouts = []
   
      if (global.nextTick) return global.nextTick
   
      if (!global.postMessage || global.ActiveXObject)
        return function(fn) {
          setTimeout(fn, 0)
        }
   
      global.addEventListener('message', function(e) {
        if (e.source === global && e.data === msgName) {
          e.stopPropagation && e.stopPropagation();
          timeouts.length && timeouts.shift()()
        }
      }, false)
   
      return function(fn) {
        timeouts.push(fn);
        global.postMessage(msgName, '*')
      }
   
    }(window))
};
</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
;
(function loop(i) {
  if (--i) setTimeout(loop, 5)
  else deferred.resolve()
}(100))
pending…
nextTick
// async test
;
(function loop(i) {
  if (--i) nextTick(loop)
  else deferred.resolve()
}(100))
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