Promise vs Callback

JavaScript performance comparison

Revision 14 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() {
  var array = new Uint8Array(10);
  for (var i = 0; i < array.length; i++) {
    array[i] = i % 256;
  }
  window.blob = new Blob([array]);
  

};
</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 readBlob(blob, fileReader, callback) {
  fileReader.readAsArrayBuffer(blob);
  fileReader.onload = callback
}
function getData(callback) {
  var i = 0;
  var fileReader = new FileReader;
  var lastByte = undefined;

  function doNextIteration(event) {
    if (i == blob.size) return callback("data");
    readBlob(blob, fileReader, doNextIteration);
    i++;
  }
  doNextIteration();
}

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

function readBlobPromise(blob, fileReader, start, end) {
  return new Promise(function(resolve, reject) {
    fileReader.readAsArrayBuffer(blob);
    fileReader.onload = resolve;
  });
}
function getData() {
  var i = 0;
  var fileReader = new FileReader;

  function doNextIteration() {
    i++;
    if (i === blob.size) return "data";
    return readBlobPromise(blob, fileReader)
      .then(doNextIteration);
  }
  return doNextIteration();
}

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

function readBlobPromise(blob, fileReader, start, end) {
  var deferred = Q.defer();
  fileReader.readAsArrayBuffer(blob);
  fileReader.onload = deferred.resolve;
  return deferred.promise;
}
function getData() {
  var i = 0;
  var fileReader = new FileReader;

  function doNextIteration() {
    i++;
    if (i === blob.size) return "data";
    return readBlobPromise(blob, fileReader)
      .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