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:
I always assumed that RemovedAt was O(1) for Lists. Is that the case?
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.
The RemoveAt() method in C# is used to remove an element in a list at a position you set.
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.
It's O(n). It even says so on MSDN.
This method is an O(n) operation, where n is (Count - index).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With