简体   繁体   中英

Javascript array sort speed affected by string length?

Just wondering, I have seen diverging opinions on this subject.

If you take an array of strings, say 1000 elements and use the sort method. Which one would be faster? An array in which the strings are 100 characters long or one in which the strings are only 3 characters long?

I tried to test but I have a bug with Firebug at the moment and Date() appears too random.

Thank you!

It depends what the strings contain, if they contain different characters, the rest of the string doesn't have to be checked for comparison so it doesn't matter.

For example, "abc" < "bca" Here only the first character had to be checked.

You can read the specs for this: http://ecma-international.org/ecma-262/5.1/#sec-11.8.5

Specifically:

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 .

It really depends on how different the strings are, but I guess the differences would be minimal due to the fact that what's called to do the comparison is way slower than actually comparing the strings.

But then again, modern browsers use some special optimizations for sort , so they cut some comparisons to speed things up. And this would happen more often sorting an array of short strings.

And FYI, if you want to make some benchmark, use a reliable tool like jsPerf .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM