Encoding XHR image data (v23)

Revision 23 of this benchmark created on


Preparation HTML

<img id="image">
<script>
   var buffer = null;
   var type = null;
   // Get the image into the cache as we are not testing the network speed
   var req = new XMLHttpRequest();
   req.overrideMimeType('text/plain; charset=x-user-defined');
   req.open('GET', 'http://jonathanleighton.com/images/me.jpg', true);
   req.responseType = 'arraybuffer';
   req.onload = function() {
      buffer = req.mozResponseArrayBuffer || req.response;
      type = req.getResponseHeader('Content-Type');
   }
   req.send(null);

   function test(func) {
      var runs = 20, complete = 0;
      for (var i = 0; i < runs; i++) {
         func(onend);
      }
      function onend(deferred) {
         if (++complete === runs) {
            deferred.resolve();
         }
      }
   }
  
   image = document.getElementById('image')
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
readAsDataURL
// async test
test(function(onend) {
   var blob = new Blob([buffer], {type: type});
   var fr = new FileReader();
   fr.onload = function() {
      image.src = fr.result;
      onend(deferred);
   };
   fr.readAsDataURL(blob);
});
ready
readAsBinaryString + btoa
// async test
test(function(onend) {
   var blob = new Blob([buffer], {type: type});
   var fr = new FileReader();
   fr.onload = function() {
      var binary = fr.result;
      image.src = "data:" + type + ";base64," + window.btoa(binary);
      onend(deferred);
   };
   fr.readAsBinaryString(blob);
});
ready
fromCharCode + btoa
test(function() {
   var binary = '';
   var bytes = new Uint8Array(buffer);
   var bytesLen = bytes.byteLength;
   for (var i = 0; i < bytesLen; i++) {
      binary += String.fromCharCode(bytes[i]);
   }
   image.src = "data:" + type + ";base64," + window.btoa(binary);
});
ready
fromCharCode.apply + btoa
test(function() {
   var bytes = new Uint8Array(buffer);
   var binary = String.fromCharCode.apply(null, bytes);
   image.src = "data:" + type + ";base64," + window.btoa(binary);
});
ready

Revisions

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