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 CCBot 2.0.0 / Other 0.0.0
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…

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.

0 Comments