Is it faster to add to a collection then sort it, or add to a sorted collection?

前端 未结 7 1603
忘掉有多难
忘掉有多难 2020-11-28 04:36

If I have a Map like this:

HashMap map;

and I want to obtain a collection of values sorted us

7条回答
  •  隐瞒了意图╮
    2020-11-28 05:10

    Inserting in a SortedSet is O(log(n)) (BUT! the current n and not the final n). Inserting in a List is 1.

    Sorting in a SortedSet is already included in inserting, so it is 0. Sorting in a List is O(n*log(n)).

    So SortedSet total complexity is O(n * k), k < log(n) for all cases but the last. Instead, List total complexity is O(n * log(n) + n), so O(n * log(n)).

    So, SortedSet mathematically has the best performance. But in the end, you have a Set instead of a List (because SortedList doesn't exist) and Set provides you fewer features than List. So in my opinion, the best solution for available features and performance is the one proposed by Sean Patrick Floyd:

    • use a SortedSet for inserting,
    • put the SortedSet as a parameter for creating a List to return.

提交回复
热议问题