只是想知道,我在这个问题上看到了不同的意见。
如果您采用一个字符串数组,假设有 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
- 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.)
- If px is a prefix of py, return true.
- 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.)
- Let m be the integer that is the code unit value for the character at position k within px.
- Let n be the integer that is the code unit value for the character at position k within py.
- If m < n, return true. Otherwise, return false.
关于Javascript数组排序速度受字符串长度影响吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11440942/