Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why localeCompare can be faster than Collator.compare

Tags:

javascript

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.

like image 831
NiedziolkaMichal Avatar asked Oct 19 '25 19:10

NiedziolkaMichal


1 Answers

One possible explanation for this in v8-based browsers like Chrome is that localeCompare has an optimization for comparing ASCII-only strings which makes use of lookup tables to compare on L1 and L3. I tried comparing strings containing non-ASCII characters here and got similar results for both localeCompare and Intl.Collator.

like image 146
Josh Brobst Avatar answered Oct 22 '25 08:10

Josh Brobst



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!