Background:
So I need to sort lots of strings. Arrays of strings, actually, but that's besides the point. What isn't is that I need to implement my own sorter function, as detailed in the linked question.Performance is quite important to me. jFriend00 very helpfully suggested that I use String.prototype.localeCompare
. The arrays I'm sorting are 100K+ elements long, and so performance is pretty important. On the MDN doc for .localeCompare
, under Performance
, it says:
When comparing large numbers of strings, such as in sorting large arrays, it is better to create an Intl.Collator object and use the function provided by its compare property.
Using it seems pretty straightforward, and the implementation of jFriend's function as the following would seem to be functionally equivalent:
data = (function(arrE2){
var nIC = new Intl.Collator,
cmp = nIC.compare.bind(nIC);
return arrE2.concat().sort(function(a, b) {
var comp, i;
for (i = 0; i < Math.min(a.length, b.length); i++) {
if ((comp = cmp(a[i], b[i])) !== 0) return comp;
}
return (a.length > b.length) - (a.length < b.length);
});
})(data);
(Please do correct me if it does anything different than jFriend's solution.)
However, what isn't clear to me is whether or not this will yield any significantly superior performance, and if so, then how. MDN could certainly do a way better job explaining, since the linked page for Intl.Collator doesn't even make so much as a mention of "performance." So I'm just left to my own devices.. I'm a n00b, so my intuition is fairly worthless, but the only way that I can think for this to augment performance is if the canonical alternative needs to load the whole locale into memory all over again for each individual comparison, while this retains the allocated memory to store the locale data in the object.
My questions are:
- Are the two identical in behavior?
- Is my new version superior as performance goes, and if so, is it significantly?