Promise vs Callback

JavaScript performance comparison

Revision 13 of this test case created by Yonathan Randolph

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 = 10;

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

function getData(callback) {
  var i = 0;
  function doNextIteration() {
    i++;
    if (i == n) callback("data");
    else setTimeout(doNextIteration, 1);
  }
  doNextIteration();
}

getData(function(data) {
  d.resolve()
})
pending…
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) {
      setTimeout(resolve, 1);
    }).then(doNextIteration);
  }
  return doNextIteration();
}

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

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

getData().then(function(data) {
  d.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.

0 Comments