Promise vs Callback

JavaScript performance comparison

Revision 25 of this test case created by Trol

Preparation code

<script src="https://cdnjs.cloudflare.com/ajax/libs/q.js/1.0.0/q.min.js"></script>
      
<script>
Benchmark.prototype.setup = function() {
  window.n = 1000;

};
</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
Promise
// async test
var d = deferred;

function getData() {
  var i = 0;

  function doNextIteration() {
    i++;
    if (i === n) return "data";
    return new Promise(function(resolve, reject) {
      resolve();
    }).then(doNextIteration);
  }
  return doNextIteration();
}

getData().then(function(data) {
  setTimeout(function() {
    d.resolve();
  }, 0)
})
pending…
Q
// async test
var d = deferred;

function getData() {
  var i = 0;

  function doNextIteration() {
    i++;
    if (i === n) return "data";
    var deferred = Q.defer();
    deferred.resolve();
    return deferred.promise.then(doNextIteration);
  }
  return doNextIteration();
}

getData().then(function(data) {
  setTimeout(function() {
    d.resolve();
  }, 0)
})
pending…
Callback
// async test
var d = deferred;

function getData(callback) {
  var i = 0;

  function doNextIteration() {
    i++;
    if (i == n) callback("data");
    else setTimeout(doNextIteration);
  }
  setTimeout(doNextIteration);
}

getData(function(data) {
  setTimeout(function() {
    d.resolve();
  }, 0)
})
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