Testing Array Explosion

JavaScript performance comparison

Revision 6 of this test case created by Slipp Douglas

Preparation code

<script>
  var possibles = [],
      c = [{
      w: 1
    }, {
      w: 2
    }, {
      w: 4
    }, {
      w: 10
    }, {
      w: 10
    }, {
      w: 1
    }, {
      w: 50
    }, {
      w: 3
    }, {
      w: 100
    }, {
      w: 5
    }, {
      w: 60
    }, {
      w: 3
    }, {
      w: 4
    }, {
      w: 9
    }, {
      w: 40
    }],
    l = c.length,
    target = 0;
</script>
<script>
Benchmark.prototype.setup = function() {
    var RAND = Math.random();
};
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
Tricky
possibles = [];

possibles = c.map(function(elem) {
  return new Array(elem.w + 1);
}).reduce(function(p, a, c, k) {
  return p.concat(a.join(c).split('').map(function(elem) {
    return Number(elem);
  }));
}, possibles);

target = Math.floor(RAND * possibles.length);
pending…
Not so tricky
possibles = [];

for (var i = 0; i < l; i++) {
  for (var j = 0; j < c[i].w; j++) {
    possibles.push(i);
  }
}

target = Math.floor(RAND * possibles.length);
pending…
Slightly tricky
possibles = [];
var tmp = [];

for (var i = 0; i < l; i++) {
    possibles.push(new Array(c[i].w + 1).join(i).split(''));
}

for (var i = 0; i < l; i++) {
    tmp.concat(possibles[i]);
}

target = Math.floor(RAND * tmp.length);
pending…
Slipp Tricky, by Slipp
l = c.length;
var total = 0;

while (l--) {
        total += c[l].w;
}

var targetWeightOffset = RAND * total;

var targetWeightOffsetRemaining = targetWeightOffset;
for (var cI = 0, cLength = c.length; cI < cLength; ++cI) {
        targetWeightOffsetRemaining -= c[cI].w;
       
        if (targetWeightOffsetRemaining <= 0) {
                target = cI;
                break;
        }
}
 
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. Here’s a list of current revisions for this page:

0 comments

Add a comment