Web Worker JSON vs String

Benchmark created by lexander on


Description

Comparing the run times of web workers when passing a JSON object vs passing a string that must be parsed in order to be worked with, and now also compared to using transferable object.

Setup

function b64ToUint6 (nChr) {
    
      return nChr > 64 && nChr < 91 ?
          nChr - 65
        : nChr > 96 && nChr < 123 ?
          nChr - 71
        : nChr > 47 && nChr < 58 ?
          nChr + 4
        : nChr === 43 ?
          62
        : nChr === 47 ?
          63
        :
          0;
    
    }
    // utility to convert base64 to array or arrayBuffer from Mozilla.
    function base64DecToArr (sBase64, nBlocksSize) {
    
      var
        sB64Enc = sBase64.replace(/[^A-Za-z0-9\+\/]/g, ""), nInLen = sB64Enc.length,
        nOutLen = nBlocksSize ? Math.ceil((nInLen * 3 + 1 >> 2) / nBlocksSize) * nBlocksSize : nInLen * 3 + 1 >> 2, taBytes = new Uint8Array(nOutLen);
    
      for (var nMod3, nMod4, nUint24 = 0, nOutIdx = 0, nInIdx = 0; nInIdx < nInLen; nInIdx++) {
        nMod4 = nInIdx & 3;
        nUint24 |= b64ToUint6(sB64Enc.charCodeAt(nInIdx)) << 18 - 6 * nMod4;
        if (nMod4 === 3 || nInLen - nInIdx === 1) {
          for (nMod3 = 0; nMod3 < 3 && nOutIdx < nOutLen; nMod3++, nOutIdx++) {
            taBytes[nOutIdx] = nUint24 >>> (16 >>> nMod3 & 24) & 255;
          }
          nUint24 = 0;
    
        }
      }
    
      return taBytes;
    }
    
    
    var parseCode = "self.onmessage = function (e) { self.postMessage(e.data); };";
    
    var passCode = "self.onmessage = function (e) { self.postMessage(e.data); }";
    
    var transferCode = "self.onmessage = function (e) { self.postMessage(e.data, [e.data]); }";
    
    var parseBlob = new Blob([parseCode], {
      type: 'text/javascript'
    });
    
    var passBlob = new Blob([passCode], {
      type: 'text/javascript'
    });
    
    var transferBlob = new Blob([transferCode], {
      type: 'text/javascript'
    });
    var aWorker = new Worker(window.URL.createObjectURL(parseBlob));
    var bWorker = new Worker(window.URL.createObjectURL(passBlob));
    var cWorker = new Worker(window.URL.createObjectURL(transferBlob));
    
    var transferObject = base64DecToArr("QmFzZSA2NCDigJQgTW96aWxsYSBEZXZlbG9wZXIgTmV0d29yaw==").buffer;

Teardown


    aWorker.terminate();
    bWorker.terminate();
    cWorker.terminate();
  

Test runner

Ready to run.

Testing in
TestOps/sec
Pass JSON
aWorker.postMessage({
  string: 'hello'
});
ready
Pass String
bWorker.postMessage('hello');
ready
Transfer Object
cWorker.postMessage(transferObject, [transferObject]);
ready

Revisions

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

  • Revision 1: published by lexander on
  • Revision 2: published by lexander on
  • Revision 3: published by bracket on
  • Revision 4: published by fafsdfssad on
  • Revision 5: published on