Summing per type

JavaScript performance comparison

Revision 2 of this test case created

Preparation code

<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.2/underscore-min.js">
</script>
<script>
Benchmark.prototype.setup = function() {
    // set up a 1 million item array
    var bigData = [],
        types = "ABCDEF".split(''),
        typesLength = types.length;
    _(1000000).times(function(i) {
      bigData.push({
        type: types[_.random(0, typesLength - 1)],
        val: _.random(1, 10)
      });
    });
};
</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
Object Hash for Total Per Type
var totalPerType = {};
for (var i = 0, len = bigData.length; i < len; ++i) {
  totalPerType[bigData[i].type] = totalPerType[bigData[i].type] || 0;
  totalPerType[bigData[i].type] += bigData[i].val;
}
var out = _.map(totalPerType, function(sum, type) {
  return {
    'type': type,
    'total': sum
  };
});
pending…
Without creating intermediate hash
var out = [];
for (var i = 0, len = bigData.length; i < len; ++i) {
  var totalObj = _.find(out, function(x) {
    return x.type == bigData[i].type;
  });
  if (!totalObj) out.push({
    'type': bigData[i].type,
    'total': bigData[i].val
  });
  else totalObj.total += bigData[i].val;
}
pending…
Nevir's reduce solution
var summed_by_type = _(bigData).reduce(function(mem, d) {
  mem[d.type] = (mem[d.type] || 0) + d.val
  return mem
}, {});

out = _(summed_by_type).map(function(v, k) {
  return {
    type: k,
    total: v
  }
});
pending…
lazyberezovsky's map-reduce solution
var groups = _(bigData).groupBy('type');

var out = _(groups).map(function(g, key) {
  return {
     type: key,
     val: _(g).reduce(function(m,x) { return m + x.val; }, 0)
  };
});
pending…
Object Hash for Total Per Type - single assignment
var totalPerType = {};
for (var i = 0, len = bigData.length; i < len; ++i) {
  totalPerType[bigData[i].type] += (totalPerType[bigData[i].type] || 0) + bigData[i].val;
}
var out = _.map(totalPerType, function(sum, type) {
  return {
    'type': type,
    'total': sum
  };
});
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