Sunday, 8 October 2023

Why localeCompare can be faster than Collator.compare

I have read multiple articles and comments, saying that the usage of Intl.Collator is beneficial in terms of performance while comparing strings. EcmaScript documentation states that localeCompare is just using Collator under the hood, but it might create the new Collator instance per each function call.

That makes sense to me, but I have tested the performance of both options, and the results are surprising. I have created an array of 50000 strings, where each string is a set of 15 lowercase English characters. Then I compared the speed of array.sort((a, b) => a.localeCompare(b)) and array.sort(collator.compare) and created a benchmark, which you can see for yourself here: https://www.measurethat.net/Benchmarks/Show/27780/0/intlcollatorcompare-vs-localecompare

The consistent result, is that localeCompare is twice as fast in this case. Could you please help me understand why is that?

Note: If I would pass the second argument(for example 'pl') to localeCompare, it would greatly decrease its performance.



from Why localeCompare can be faster than Collator.compare

No comments:

Post a Comment