WebWorker vs Single Thread (v7)

Revision 7 of this benchmark created by Cong Liu 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(1e8);
ready
1 thread (Worker)
// async test
parallel(1e8,1)
ready
2 threads
// async test
parallel(1e8,2)
ready
3 threads
// async test
parallel(1e8,3)
ready
4 threads
// async test
parallel(1e8,4)
ready

Revisions

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