在Javascript中以降序对字符串进行排序(最有效)? [英] Sorting strings in descending order in Javascript (Most efficiently)?

查看:76
本文介绍了在Javascript中以降序对字符串进行排序(最有效)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

W3CSchools具有以下示例:

W3CSchools has this example:

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
fruits.reverse();

这是在Javascript中按降序对字符串进行排序的最有效方法吗?

Is this the most efficient way to sort strings in descending order in Javascript?

答案之一是使用localeCompare.只是好奇是否我们执行reverse(),这对所有语言环境都有效(也许这是一个单独的问题-请在评论中让我知道)?

One of the answers is using localeCompare. Just curious whether if we do reverse(), will that work for all locales (Maybe this is a separate question - Just let me know in the comments)?

推荐答案

如果您考虑

obj.sort().reverse();

VS

obj.sort((a, b) => (a > b ? -1 : 1))

VS

obj.sort((a, b) => b.localeCompare(a) )

性能优胜者是:obj.sort().reverse().

The performance winner is : obj.sort().reverse().

使用10.000个元素的数组进行测试,obj.sort().reverse()的速度比obj.sort( function )(Chrome除外)和obj.sort( function )(使用localCompare)要快.

Testing with an array of 10.000 elements, obj.sort().reverse() is faster than obj.sort( function ) (except on chrome), and obj.sort( function ) (using localCompare).

此处的性能测试:

var results = [[],[],[]]

for(let i = 0; i < 100; i++){
  const randomArrayGen = () => Array.from({length: 10000}, () => Math.random().toString(30));
  const randomArray = randomArrayGen();
  const copyArray = x => x.slice();

  obj = copyArray(randomArray);
  let t0 = performance.now();
  obj.sort().reverse();
  let t1 = performance.now();

  obj = copyArray(randomArray);
  let t2 = performance.now();
  obj.sort((a, b) => (a > b ? -1 : 1))
  let t3 = performance.now();

  obj = copyArray(randomArray);
  let t4 = performance.now();
  obj.sort((a, b) => b.localeCompare(a))
  let t5 = performance.now();  

  results[0].push(t1 - t0);
  results[1].push(t3 - t2);
  results[2].push(t5 - t4);  
}

const calculateAverage = x => x.reduce((a,b) => a + b) / x.length ;

console.log("obj.sort().reverse():                   " + calculateAverage(results[0]));
console.log("obj.sort((a, b) => (a > b ? -1 : 1)):   " + calculateAverage(results[1]));
console.log("obj.sort((a, b) => b.localeCompare(a)): " + calculateAverage(results[2]));

这篇关于在Javascript中以降序对字符串进行排序(最有效)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆