WebWorker vs Single Thread (v19)

Revision 19 of this benchmark created by semoon on


Setup

window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL || window.oURL;
    
    function parallel(t, count) {
      count = count || 4;
      var threads = [];
      var step = Math.ceil(t / count);
      var sum = 0;
      var code = 'function calc(from, to){var sum = 0; for(var i = from; i<= to; i++) sum += i;return sum;} onmessage = function(e) {postMessage(calc(e.data.from, e.data.to));close();}';
      var bb = new Blob([code], {
        type: 'text/javascript'
      });
      var bbURL = URL.createObjectURL(bb);
      for (var from = 1, to = step; from <= t; from += step, to += step) {
        var worker = new Worker(bbURL);
        worker.onmessage = function(e) {
          sum += e.data;
          if (--count === 0) {
            threads = null;
            URL.revokeObjectURL(bbURL);
            deferred.resolve();
          }
        };
        worker.postMessage({
          from: from,
          to: (to > t ? t : to)
        });
        //console.log({from: from, to: (to > t? t: to)});
        threads.push(worker);
      }
    }
    
    function single(t) {
      var sum = 0;
      for (var i = 1; i <= t; i++)
        sum += i;
      return sum;
    }

Test runner

Ready to run.

Testing in
TestOps/sec
Single thread
single(1e6);
ready
1 thread (Worker)
// async test
parallel(1e6, 1)
ready
2 threads
// async test
parallel(1e6, 2)
ready
4 threads
// async test
parallel(1e6, 4)
ready
8 threads
// async test
parallel(1e6, 8)
ready

Revisions

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