[英]Frequent inserts into sorted collection
I have sorted collection (List) and I need to keep it sorted at all times. 我已经对集合(List)进行了排序,我需要始终对其进行排序。
I am currently using List.BinarySearch on my collection and then insert element in right place. 我目前正在我的集合上使用List.BinarySearch,然后在正确的位置插入元素。 I have also tried sorting list after every insertion but the performance in unacceptable. 我也尝试过每次插入后的排序列表,但性能不可接受。
Is there a solution that will give better performance? 有没有可以提供更好性能的解决方案? Maybe I should use other collection. 也许我应该使用其他收藏品。
(I am aware of SortedList but it is restricted to unique keys) (我知道SortedList但它仅限于唯一键)
If you're using .Net 4, you can use a SortedSet<T>
如果您使用的是.Net 4,则可以使用SortedSet<T>
http://msdn.microsoft.com/en-us/library/dd412070.aspx http://msdn.microsoft.com/en-us/library/dd412070.aspx
For .Net 3.5 and lower, see if a SortedList<TKey,TValue>
works for you. 对于.Net 3.5及更低版本,请查看SortedList<TKey,TValue>
是否适合您。
http://msdn.microsoft.com/en-us/library/ms132319.aspx http://msdn.microsoft.com/en-us/library/ms132319.aspx
PowerCollections has an OrderedBag
type which may be good for what you need. PowerCollections有一个OrderedBag
类型,可能对你需要的东西有好处。 From the docs 来自文档
Inserting , deleting, and looking up an an element all are done in log(N) + M time , where N is the number of keys in the tree, and M is the current number of copies of the element being handled. 插入 ,删除和查找元素都是在log(N)+ M时间内完成的 ,其中N是树中键的数量,M是正在处理的元素的当前副本数。
However, for the .NET 3.5 built in types, using List.BinarySearch
and inserting each item into the correct place is a good start - but that uses an Array internally so your performance will drop due to all the copying you're doing when you insert. 但是,对于.NET 3.5内置类型,使用List.BinarySearch
并将每个项目插入正确的位置是一个良好的开端 - 但是在内部使用数组,因此当您执行所有复制时,性能将下降插入。
If you can group your inserts into batches that will improve things, but unless you can get down to only a single sort operation after all your inserting you're probably better off using OrderedBag
from PowerCollections
if you can. 如果你可以将插件分组到可以改进的东西,但除非你在所有插入后只能进行一次排序操作,否则如果可以的话,最好使用PowerCollections
OrderedBag
。
尝试将插入聚合为批次,并仅在每批次结束时进行排序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.