C#列表的速度 [英] Speed of C# lists
问题描述
C#列出的速度很快吗?使用列表处理对象的利弊有哪些?
Are C# lists fast? What are the good and bad sides of using lists to handle objects?
广泛使用列表会使软件变慢吗?在C#中,列表的替代方法是什么?
Extensive use of lists will make software slower? What are the alternatives to lists in C#?
列表的对象太多"是多少个对象?
How many objects is "too many objects" for lists?
推荐答案
List<T>
使用支持数组来保存项目:
List<T>
uses a backing array to hold items:
- 索引器访问(即获取/更新)为O(1)
- 从尾部移除为O(1)
- 从其他地方移走要求将现有物品上移,因此O(n)有效
- 添加到末尾为O(1),除非需要调整大小,在这种情况下为O(n). (这使缓冲区的大小增加了一倍,因此摊销成本为O(1).)
- 添加到其他位置要求将现有项目下移,因此O(n)有效
- 除非对项目进行排序,否则查找项目为O(n),在这种情况下,二进制搜索会给出O(log n)
通常可以相当广泛地使用列表.如果您知道在开始填充列表时的最终大小,则最好使用允许您指定容量的构造函数,以避免调整大小.除此之外:如果您担心的话,请展开探查器...
It's generally fine to use lists fairly extensively. If you know the final size when you start populating a list, it's a good idea to use the constructor which lets you specify the capacity, to avoid resizing. Beyond that: if you're concerned, break out the profiler...
这篇关于C#列表的速度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!