According to the MSDN documentation on the List<T>.Clear :
This method is an O (n) operation where n is a graph.
Why is O (n)? I ask because I suppose that cleaning List<T> can be done simply by allocating a new array T[] inside. No other class can reference this array, so I see no harm in this approach.
Now, maybe this is a stupid question ... does the array T[] O (n) allocate? For some reason, I would not have thought so; but maybe it is (do I have a lack of CS degree showing right now?). If this is the case, I suppose that would explain it, because, according to the same documentation above, the capacity of the list remains unchanged, which means that you need to build an array of equal size.
(Again, this does not look like it could be the correct explanation, since then the documentation should have indicated "where n is Capacity" - not Count *).
I just suspect that this method, instead of allocating a new array, resets all elements of the current; and I'm curious to know why this would be.
* Hans Passant indicated in the commentary on the LukeH answer that the documents are correct. Clear only resets the elements that were set to List<T> ; he does not need to "re-zero" all the elements behind them.
Dan tao
source share