gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 03:13:23 26 4
gpt4 key购买 nike

给定一个列表:

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com