C#比SortedList <>更快排序

我们有一个

SortedList<Resource, Resource> resources =
    new SortedList<Resource, Resource>(new ResourceIdle());

我们在模拟中使用的.这个资源列表以这种方式初始化,因为我们希望在任何时间点传递不同的比较器.我们遇到的第一个问题是SortedList<>需要在比较器中进行额外的比较,以便我们可以添加具有相同属性的不同Resource实例.例如,如果Comparer看起来像:

public int Compare(Resource x, Resource y)  
{  
    int priority1 = x.Priority;    
    int priority2 = y.Priority;    

    if (priority1 > priority2) { 
      return -1;  
    } else if (priority1 < priority2) {  
      return 1;  
    } else {  
      return (x.Id.CompareTo(y.Id));  
    }  
}  

然后,当优先级相同时,我们必须进行额外的比较,否则我们会返回具有相同键的条目的异常.所以我的问题是,还有另一种实现这一目标的方法吗?而作为次要问题,有什么比SortedList<>更快的速度.订购大量物品?

最佳答案
好吧,SortedDictionary<,>具有不同的性能特征 – 它取决于您正在使用它做什么. MSDN比较两者有很多细节:

The SortedDictionary<TKey, TValue> generic class is a binary search tree with O(log n) retrieval, where n is the number of elements in the dictionary. In this respect, it is similar to the SortedList<TKey, TValue> generic class. The two classes have similar object models, and both have O(log n) retrieval. Where the two classes differ is in memory use and speed of insertion and removal:

  • SortedList<TKey, TValue> uses less memory than SortedDictionary<TKey, TValue>.
  • SortedDictionary<TKey, TValue> has faster insertion and removal operations for unsorted data: O(log n) as opposed to O(n) for SortedList<TKey, TValue>.
  • If the list is populated all at once from sorted data, SortedList<TKey, TValue> is faster than SortedDictionary<TKey, TValue>.

转载注明原文:C#比SortedList <>更快排序 - 代码日志