Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How expensive is list.RemoveAt(0) for a generic list?

Tags:

C#, .NET4.

We have some performance critical code that is causing some problems. It is sort of a modified queue which is in fact being backed by a List. I was wondering how expensive removing an element at index 0 is. Questions that come to mind are:

  • Depending on how List is backed, do any memory allocations/deallocations happen after at RemoveAt() for compensating for the new size of the list? I know, for example, that resizing an array can be expensive (relatively speaking)
  • I always imagined Lists to behave like linked-lists, such that removing an element at the zero position would mean simply having the start-of-list reference adjusted from the previous zero element to what used to be the 1st element (but is now the first element). But, my 'imagination' and reality are not always in line.

I always assumed that RemovedAt was O(1) for Lists. Is that the case?

like image 461
CoolUserName Avatar asked May 18 '11 23:05

CoolUserName


People also ask

Is list a generic C#?

In c#, List is a generic type of collection, so it will allow storing only strongly typed objects, i.e., elements of the same data type. The size of the list will vary dynamically based on our application requirements, like adding or removing elements from the list.

What is use of RemoveAt?

The RemoveAt() method in C# is used to remove an element in a list at a position you set.


2 Answers

List<T> is backed by a simple array, plus a size field that indicates which portion of the array is actually in use. (to allow for future growth). The array isn't resized unless you add too many elements or call TrimExcess.

Remove is O(n), since it needs to shift the rest of the list down by one.


Instead, you can use a LinkedList<T> (unless you use random access), or write your own list which tracks an empty portion in front.

like image 97
SLaks Avatar answered Oct 11 '22 13:10

SLaks


It's O(n). It even says so on MSDN.

This method is an O(n) operation, where n is (Count - index).

like image 43
Jeff Mercado Avatar answered Oct 11 '22 15:10

Jeff Mercado