setTimeout vs nextTick polyfill

JavaScript performance comparison

Test case created by Kevin Ennis

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, 0)
  else deferred.resolve()
}(100))
pending…
nextTick
// async test
;(function loop(i){
  if (--i) nextTick(loop)
  else deferred.resolve()
}(100))
pending…

You can edit these tests or add even more tests to this page by appending /edit to the URL.

Compare results of other browsers

0 comments

Add a comment