Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is List(T).Clear O(N)?

According to the MSDN documentation on the List<T>.Clear method:

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

Why O(n)? I ask because I would assume that clearing a List<T> could be accomplished simply by allocating a new T[] array internally. No other class could have a reference to this array, so I fail to see the harm in this approach.

Now, maybe this is a stupid question... is allocating a T[] array itself O(n)? For some reason I would not have thought so; but maybe it is (is my lack of a C.S. degree showing right now?). If so, I suppose that would explain it since, according to the same documentation quoted above, the capacity of the list remains unchanged, which means an array of equal size would need to be constructed.

(Then again, this doesn't seem like it could be the correct explanation, as then the documentation should have said "where n is Capacity"—not Count*).

I just suspect that this method, rather than allocating a new array, zeroes out all elements of the current one; and I'm curious to know why this would be.

*Hans Passant pointed out in a comment to LukeH's answer that the docs are correct. Clear only zeroes out the elements that have been set in the List<T>; it does not need to "re-zero" all the elements past those.

like image 750
Dan Tao Avatar asked Feb 02 '23 22:02

Dan Tao


1 Answers

As far as I'm aware the current implementation just calls Array.Clear on its internal T[] array, and Array.Clear is an O(n) process. (As Hans points out in the comments, the MSDN docs are correct that the n in this case is the list's Count, not its Capacity.)

But, even if it did just allocate a new T[] array internally, that would still be an O(n) process because allocating an array of size n involves initialising all n elements to their zero/null/default state.

Of course, there's nothing to stop some sort of internal trickery where the array could be initialised with length 0 or 42 or whatever and then auto-expanded again on-the-fly as required, amortising the overall O(n) cost.

like image 114
LukeH Avatar answered Feb 05 '23 19:02

LukeH