Difference in performance between calling .localeCompare on string objects and constructing a purpose-made Intl.Collator object?

荒凉一梦 提交于 2019-12-11 03:11:33

问题


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?

回答1:


I'm having a similar issue and found this jsperf really useful.

Bottom line: Yes, Intl.Collator is almost twice as fast than a.localeCompare(b).



来源:https://stackoverflow.com/questions/19993639/difference-in-performance-between-calling-localecompare-on-string-objects-and-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!