Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 950
abenci Avatar asked Jul 09 '10 10:07

abenci


People also ask

How to Remove index from List in c#?

The RemoveAt() method takes a zero-based index number as a ​parameter and removes the item at that index.

What method do you use to remove an item from a list t at a specific index?

RemoveAt (Int32) Method is used to remove the element at the specified index of the List<T>. Properties of List: It is different from the arrays.

How does list Remove Work C#?

The Remove method removes the first occurrence of a specific object from a List. The Remove method takes an item as its parameter. We can use the RemoveAt method to remove an item at the specified position within a List. The Remove method removes the first occurrence of a specific object from a List.


1 Answers

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.

like image 179
Noldorin Avatar answered Oct 24 '22 13:10

Noldorin