c# - List.Insert 有任何性能损失吗?

标签 c# list time-complexity

给定一个列表:

List<object> SomeList = new List<object>();

正在做:

SomeList.Insert(i, val);

对比

SomeList.Add(val);

有任何性能损失吗?如果是,如何取决于:
- i - 插入索引
- SomeList.Count - 列表的大小

最佳答案

The List class is the generic equivalent of the ArrayList class. It implements the IList generic interface using an array whose size is dynamically increased as required.

( source )

这意味着内部数据存储为数组,因此执行插入可能需要将所有元素移过去以腾出空间,因此其复杂度为 O( N),而 add 是一个(摊销的)常数时间 O(1) 操作,所以

总结 - 是的,它几乎总是会变慢,而且列表越大,它就会越慢。

关于c# - List.Insert 有任何性能损失吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18587267/

相关文章:

c# - 如何生成均匀分布的游戏对象并沿圆形路径移动它们?

c# - WCF 消息安全实际上是否加密消息内容?

java - 为什么java中Collections的fill(),copy(),reverse(),shuffle()是这样实现的

python - 当子字符串匹配时如何映射两个列表中的值

scala - 如何在scala中对列表列表执行转置?

java - 遍历列表值的 HashMap 的替代方案?

c# - 保护条款不触发

c# - 使用 Zxing 库、Xamarin.android 应用程序扫描时,将屏幕方向锁定为纵向。

algorithm - 在不增加复杂性的情况下反转列表顺序

algorithm - Dijkstra 算法的运行时间测量