本文介绍了List.Insert是否有任何性能上的损失?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
提供列表:
List<object> SomeList = new List<object>();
这样做:
SomeList.Insert(i, val);
VS.
SomeList.Add(val);
是否有性能损失?如果存在,它如何取决于:
-i
-插入索引
-SomeList.Count
-列表的大小
Has any performance penalty? If it does, how it depends on:
- i
- insertion index
- SomeList.Count
- The size of the list
推荐答案
(源)
意味着内部数据存储为数组,因此执行insert
可能需要将所有元素移到上方以腾出空间,因此其复杂度为O(N),而add
是(摊销)恒定时间O(1)运算,因此是.
Meaning that the internal data is stored as an Array, and so it is likely that to perform the insert
it will need to move all the elements over to make room, thus its complexity is O(N), while add
is a (amortised) constant time O(1) operation, so yes.
摘要-是的,它几乎总是比较慢,并且列表越大,它就会变得越慢.
Summary - Yes, it will almost always be slower, and it will get slower the larger your list gets.
这篇关于List.Insert是否有任何性能上的损失?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!