Javascript Array Grouping

JavaScript performance comparison

Revision 4 of this test case created

Info

different methods for grouping string in an array and getting the max value of the grouping.

Preparation code

<script>
  var arr = [];
  var day, month, year;
  for (var i = 0; i < 10000; i++) {
    day = Math.round(Math.random() * 30);
    month = Math.round(Math.random() * 12);
    year = Math.round(Math.random() * 3 + 2009);
    arr.push(month + "/" + day + "/" + year);
  }
</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
nightcracker
var group = {};
var max = 0;
var value;
for (var i = arr.length; --i >= 0;) {
  value = arr[i];
  group[value] = (group[value] || 0) + 1;
}
for (key in group) {
  if (group[key] > max) max = group[key];
}
pending…
Mike Samuel
var max = 0;
var group = {};
var value, n, len = arr.length;
for (var i = len; --i >= 0;) {
  value = arr[i];
  n = group[value] = 1 - -(group[value] | 0);
  if (n > max) {
    max = n;
  }
}
pending…
Original
var max = 0;
var group = {};
arr.map(function(value) {
  if (group[value]) {
    group[value]++;
  } else {
    group[value] = 1;
  }
  max = Math.max(max, group[value]);
});
pending…
asdf
var max = 0,
    group = {},
    value, n, gv;
for (var i = 0; i < arr.length; i++) {
  value = arr[i];
  n = group[value] = 1 + (group[value] | 0);
}
for (var key in group) {
  gv = group[key];
  if (gv > max) max = gv;
}
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