简体   繁体   English

什么是更快的collection.Insert(0,newItem)vs list.Add(newItem)+在Winforms ListView C#中排序?

[英]What is faster collection.Insert(0, newItem) vs list.Add(newItem) + Sort in Winforms ListView C#?

I have a ListView that I need to update by adding an item. 我有一个ListView,需要添加一个项目来更新。 Using .Add() will place it on the bottom. 使用.Add()会将其放在底部。 So I can then sort it by a insert time (it's one of the fields). 因此,我可以按插入时间对其进行排序(这是字段之一)。 Another option is to use Collection.Insert(0, newItem) that will put it to the top and move everything down one index. 另一种选择是使用Collection.Insert(0, newItem) ,它将放置在顶部并将所有内容向下移动一个索引。

Read somewhere that Collection.Insert(0, newItem) may be slow for larger lists b/c of the shifting. 对于较大的列表b / c,请阅读Collection.Insert(0, newItem)可能较慢的地方。 If that is the case - what would be faster? 如果是这样-会更快吗? Collection or Add + Sort? 收集还是添加+排序?

or is there another way? 还是有另一种方法?

Thanks. 谢谢。

Insert will be faster than Add + Sort, because Sorting will involve unnecessary comparisons if your list is already sorted. 插入将比添加+排序更快,因为如果列表已经排序,则排序将涉及不必要的比较。 But like others have said, it probably won't matter enough to care. 但是,就像其他人所说的那样,关心它可能已经足够了。

Unless you have millions of items, it won't matter and you're simply pre-optimizing and either will be fine. 除非您有数百万个项目,否则没有关系,您只是在进行预优化,任何一个都可以。 If you do have millions of items, then you are presenting to the user too many items. 如果您确实有数百万个项目,那么您向用户展示的项目太多了。

If your list is going to be displayed to a user, it's probably not going to be large enough for the performance difference to be noticeable. 如果您要向用户显示您的列表,则可能不会足够大,以至于性能差异不明显。 Probably use whichever makes more sense in the context. 可能使用在上下文中更有意义的那个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM