简体   繁体   中英

does Array.sort (or any collections sort method) depends on size of an individual items in C#?

As we all know the sort method the array works upon. The speed is affected by the number of items stored in an array. However would the speed be affected by the size of the individual items? I searched this over the net but i haven't found a convincing answer. Anybody got helpful links or explanation that can be displayed here?

For example we can have an array storing 100 string items which are all 20 string characters in length. Would the speed of sorting differ with 100 string items which are all 30 string characters?

Thank you

As long as it's reference types, no, the size will not matter. A reference is always the same size, no matter how large the object is that it points to, so swapping two refererences is constant time no matter what they point to.

Edit: Now that you refined the question, obviously figuring out the sorting order will take more time, the more complex comparing two objects is. If you have 100 strings of 100 characters each that differ in the first two characters, sorting them will be faster than having 100 strings of 100 characters that all contain 98 'a's and only differ in the last two.

Generally speaking, before you wonder about performance, make sure you actually have a problem. Comparing 100 strings is peanuts for todays hardware.

No. The size of an object Under the covers the sort method moves pointers in a collection, and pointers are always the same size regardless of the structure that they point at. In addition to collection size the sort method time is affected by the amount of time that it takes to compare two objects in the list.

Would the speed of sorting differ with 100 string items which are all 30 string characters?

Potentially, yes. Potentially, no. It depends. If you have a bunch of strings which only differ at character 30, that will take longer to sort than a bunch of strings which only differ at character 20 - simply because each string comparison will have more work to do. On the other hand, if you have a bunch of strings which differ in their first characters, then the comparisons will be quick no matter how many trailing characters there are.

Also note that the more data you're using, the less effective the CPU cache may be, which can make a huge difference.

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