I have an array of a couple thousand strings
['7/21/2011', '7/21/2011', '7/21/2011', '7/20/2011', etc]
I am currently, running this code to group by the string and get the max group value:
var max = 0;
var group = {};
arr.map(function (value) {
if (group[value]) {
group[value]++;
} else {
group[value] = 1;
}
max = Math.max(max, group[value]);
});
Are there any improvements to make this code run faster?
EDIT: The results are in: http://jsperf.com/javascript-array-grouping2
EDIT EDIT: that test was flawed. Mike Samuel's code was the fastest.
6000 entries test -> http://jsperf.com/javascript-array-grouping2
10K entries test -> http://jsperf.com/javascript-array-grouping
If you're sure this is a hotspot and speed is really important, I would try to cut out several thousand function calls by inlining max
and map
.
You can also make the body of your function faster by cutting out a comparison.
var max = 0;
var group = {};
for (var i = arr.length; --i >= 0;) {
var value = arr[i];
var n = group[value] = 1 - -(group[value] | 0);
if (n > max) { max = n; }
}
The best thing to do is measure on the browsers you care about.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With