Javascript数组排序速度受字符串长度影响吗?

标签 javascript sorting

只是想知道,我在这个问题上看到了不同的意见。

如果您采用一个字符串数组,假设有 1000 个元素并使用排序方法。哪一个会更快?字符串长度为 100 个字符的数组还是字符串长度仅为 3 个字符的数组?

我尝试测试,但目前 Firebug 存在一个错误,并且 Date() 显得过于随机。

谢谢!

最佳答案

这取决于字符串包含的内容,如果它们包含不同的字符,则不必检查字符串的其余部分进行比较,因此没关系。

例如,"abc" < "bca"这里只需要检查第一个字符。

您可以阅读此规范:http://ecma-international.org/ecma-262/5.1/#sec-11.8.5

具体:

Else, both px and py are Strings

  1. If py is a prefix of px, return false. (A String value p is a prefix of String value q if q can be the result of concatenating p and some other String r. Note that any String is a prefix of itself, because r may be the empty String.)
  2. If px is a prefix of py, return true.
  3. Let k be the smallest nonnegative integer such that the character at position k within px is different from the character at position k within py. (There must be such a k, for neither String is a prefix of the other.)
  4. Let m be the integer that is the code unit value for the character at position k within px.
  5. Let n be the integer that is the code unit value for the character at position k within py.
  6. If m < n, return true. Otherwise, return false.

关于Javascript数组排序速度受字符串长度影响吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11440942/

相关文章:

Python:使用字典来加速元组列表的排序

javascript - 从临时 express 服务器返回值

python 如何在不从列表中删除元素的情况下按出现次数对列表进行排序?

c++ - 按长度合并排序字符串数组

c++ - 根据重复次数对输入文本中的单词进行排序?

java - 从结果中识别出 "best bang for the buck"项

javascript - 在 Object 的情况下,Javascript 重新分配和引用如何工作?需要深入解释吗?

javascript - 使用 jQuery 动态添加和删除表列

javascript - 如何在 Node 5.6.0 环境中运行 Node 6 npm 包?

javascript - 替代加载器的 this._compilation