List.Remove(T) 或 List.RemoveAt(int) 方法哪个更快?
.NET 集合中的 List
是否比 List
方法更快?值类型或引用类型的速度是否不同?
Is List<T>.Remove(T)
faster than the List<T>.RemoveAt(int)
method in .NET collections? Is speed different for value types or reference types?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
简单答案:
一般来说,
RemoveAt
更快,但并不总是那么快。长答案:
让我们首先考虑找到合适的项目。
Remove
方法必须在列表中搜索与给定对象匹配的项目,因此通常需要O(n)
时间。列表上的RemoveAt
可以简单地索引给定的项目,因此是O(1)
。现在,从列表末尾删除一个项目当然总是
O(1)
,但通常删除一个项目需要O(n)
时间,因为重新洗牌需要待完成(将移除的一项向前移动)。因此,在一般情况下,移除的总时间复杂度为O(n) + O(n)
或O(n) + O(1)
(对于移除)和RemoveAt,因此无论哪种情况都只需O(n)
。然而,RemoveAt
保证至少同样快,尽管缩放是相同的,除非您知道要在结束时/接近结束时删除它。Simple answer:
In general,
RemoveAt
is quicker, though not always hugely.Long answer:
Let's just consider finding the appropiate item first. The
Remove
method has to search the list for the item that matches the given object, and is thusO(n)
time in general.RemoveAt
on a list can simply index the given item, and is thusO(1)
.Now, removing an item from the end of a list is always
O(1)
of course, but in general removing an item takesO(n)
time, because reshuffling needs to be done (moving items after the removed one forward). Therefore, in the general case, the total time complexity for removal is eitherO(n) + O(n)
orO(n) + O(1)
for Remove and RemoveAt respectively, hence simplyO(n)
in either case. However,RemoveAt
is guaranteed to be at least as quick, though scaling is the same unless you know you're removing it at/near the end.List.Remove(T) 在其实现中使用 IndexOf 和 RemoveAt(int)。所以 List.RemoveAt(int) 更快。
List.Remove(T) uses IndexOf and RemoveAt(int) in its implementation. So List.RemoveAt(int) is faster.
Remove(T) 在内部调用RemoveAt(int)
所以,直接执行removeAt会更快。
但你想实现什么目标?
Remove(T) makes internally a call to RemoveAt(int)
so, doing directly a removeAt is faster.
But What do you want to achieve?
鉴于 .Net 感染的是向量(或数组),而不是链表,RemoveAt() 更快。
Given that a .Net is infect a vector (or array), not a linked list, RemoveAt() is quicker.
使用 System.Diagnostics.Stopwatch()
我会创建一个小控制台应用程序来检查哪个更快。
Use
System.Diagnostics.Stopwatch()
I would have just created a little console app to check which is faster.