List.Insert是否有任何性能上的损失? [英] Does List.Insert have any performance penalty?

查看:74
本文介绍了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

推荐答案

List类是ArrayList类的通用等效项.它使用数组实现IList通用接口,该数组的大小根据需要动态增加.

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.

()

意味着内部数据存储为数组,因此执行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 insertit 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是否有任何性能上的损失?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆