400x Sorting Speedup by Switching a.localeCompare(b) to (ab?1:0))

后端 未结 5 758
无人及你
无人及你 2020-12-01 03:39

By switching a javascript sort function from

myArray.sort(function (a, b) {
  return a.name.localeCompare(b.name);
});

to

m         


        
5条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-01 04:05

    I don't know you still looking for solution to this problem

    // Defaulted to ascending
    // 1 asc | -1 desc
    var direction = 1; 
    myArray.sort(function (a, b) {
      return a.name.localeCompare(b.name) === 1 ? direction : -1 * direction;
    });
    

    i added a === 1 check to your code and this improved perf 400x that means both have comparable perf numbers.

    Perf numbers with localeCompare arr size: 3200 Avg time took in 10 repetitions : 60 ms

    Perf numbers with > approach. avg time took 55 ms

提交回复
热议问题