Sort a large collection while showing progress

后端 未结 7 798
广开言路
广开言路 2021-01-02 22:58

What is the best way to sort a collection while updating a progress bar? Currently I have code like this:

for (int i = 0; i < items.size(); i++)
{
    pro         


        
7条回答
  •  被撕碎了的回忆
    2021-01-02 23:32

    I may have missed something because nobody else has mentioned it, but it sounds like the runtime types of your source List object is not an implementor of RandomAccess and therefore your Collections.binarySearch invocation is running in O(n) time. That would slow things down quite a bit, very noticeably so, when you so much as double the number of items to sort.

    And furthermore, if you are using for example a LinkedList for sortedItems then insertion is also O(n).

    If that's the case, it makes perfect sense that when you go from 1 million to 2 million items, your expected time will also roughly double.

    To diagnose which of the 2 List objects is problematic

    1. If the progress bar is slow from the start, it's items; try using a different container, something tree-ish or hash-y
    2. If the progress bar gets slower and slower as it gets closer to 100%, it's sortedItems; same advice as above

    Note that it can be both Lists that are causing the slowdown. Also this has nothing to do with a progress bar. The problem you described is algorithmic with respect to the sorting, not the updating of a progress bar.

提交回复
热议问题