Why is List(T).Clear O(N)?
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.
Because the implementation of List<T>.Clear()
calls Array.Clear()
on the list's backign array, and per the documentation that method sets all of the elements of that array to null
.
I would guess that the reason why the existing array is cleared instead of a new one being created is that the .NET team determined that it was more efficient to clear an existing array instead of allocating a new one. Allocating a new array also takes time/memory so it's a tradeoff that tries to optimize for the common usage scenarios.