频繁插入已排序的集合
我已经对集合(列表)进行了排序,并且我需要始终保持其排序。
我目前在我的集合上使用 List.BinarySearch,然后在正确的位置插入元素。我也尝试过在每次插入后对列表进行排序,但性能不可接受。
有没有一种解决方案可以提供更好的性能?也许我应该使用其他集合。
(我知道 SortedList 但它仅限于唯一键)
I have sorted collection (List) and I need to keep it sorted at all times.
I am currently using List.BinarySearch on my collection and then insert element in right place. 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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
PowerCollections 有一个
OrderedBag
类型,可能适合您的需要。来自文档然而,对于 .NET 3.5 内置类型,使用 List.BinarySearch 并将每个项目插入正确的位置是一个好的开始 - 但它在内部使用数组,因此您的性能会由于所有插入时复制您正在执行的操作。
如果您可以将插入分组为批次,这将改善情况,但除非您在所有插入后只能进行一次排序操作,否则最好使用
PowerCollections< 中的
OrderedBag
/code> 如果可以的话。PowerCollections has an
OrderedBag
type which may be good for what you need. From the docsHowever, 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.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
fromPowerCollections
if you can.如果您使用的是 .Net 4,则可以使用
SortedSet
http://msdn.microsoft.com/en-us/library/dd412070.aspx
对于 .Net 3.5 及更低版本,请查看
SortedList适合你。
http://msdn.microsoft.com/en-us/library/ms132319。 ASPX
If you're using .Net 4, you can use a
SortedSet<T>
http://msdn.microsoft.com/en-us/library/dd412070.aspx
For .Net 3.5 and lower, see if a
SortedList<TKey,TValue>
works for you.http://msdn.microsoft.com/en-us/library/ms132319.aspx
尝试将插入聚合到批次中,并仅在每个批次的末尾进行排序。
Try to aggregate insertions into batches, and sort only at the end of each batch.