给定一个列表:
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/