Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
634 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...