Which is faster, the List<T>.Remove(T) or List<T>.RemoveAt(int) method?

一曲冷凌霜 提交于 2019-12-18 19:16:12

问题


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?


回答1:


List.Remove(T) uses IndexOf and RemoveAt(int) in its implementation. So List.RemoveAt(int) is faster.

public bool Remove(T item)
{
    int index = this.IndexOf(item);
    if (index >= 0)
    {
        this.RemoveAt(index);
        return true;
    }
    return false;
}



回答2:


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 thus O(n) time in general. RemoveAt on a list can simply index the given item, and is thus O(1).

Now, removing an item from the end of a list is always O(1) of course, but in general removing an item takes O(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 either O(n) + O(n) or O(n) + O(1) for Remove and RemoveAt respectively, hence simply O(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.




回答3:


Remove(T) makes internally a call to RemoveAt(int) so, doing directly a removeAt is faster.

But What do you want to achieve?




回答4:


Given that a .Net is infect a vector (or array), not a linked list, RemoveAt() is quicker.




回答5:


Use System.Diagnostics.Stopwatch()

I would have just created a little console app to check which is faster.



来源:https://stackoverflow.com/questions/3211679/which-is-faster-the-listt-removet-or-listt-removeatint-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!