13

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?

Community
  • 1
  • 1
abenci
  • 8,422
  • 19
  • 69
  • 134

5 Answers5

27

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.

Noldorin
  • 144,213
  • 56
  • 264
  • 302
19

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;
}
DevExpress Team
  • 11,338
  • 2
  • 24
  • 23
  • But if it make your code worst or unreadable, might as well keep using Remote(T). – Pierre-Alain Vigeant Aug 24 '10 at 16:01
  • 1
    `this.IndexOf(item)` code has a huge price in terms of performance as it scans the entire backing array until it gets the item to be deleted. Specially when the item to be removed is at the end of the list, it scans the entire list every time a deletion is requested. It happened with me when I was trying to implement a stack data structure with the help of a `List` class. As the list size grows considerably e.g. beyond 10K elements, deletion from the end using Remove(T) can wreck havoc with your program. – RBT Feb 18 '17 at 01:29
0

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

But What do you want to achieve?

cRichter
  • 1,411
  • 7
  • 7
0

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

Ian Ringrose
  • 51,220
  • 55
  • 213
  • 317
-2

Use System.Diagnostics.Stopwatch()

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

Sachith Muhandiram
  • 2,819
  • 10
  • 45
  • 94
HarveySaayman
  • 351
  • 3
  • 12