Aleksei Maide Aleksei Maide - 2 months ago 12
C# Question

Will List<T> Shrink In Size If You Remove Elements

When a

List<T>
gets full, it doubles in size, occupying twice the memory, but would it automatically decrease in size if you removed elements from it?

As much as I understand decreasing the
Capacity
would not mean relocating all the data in memory, it would just need to drop off the end of the reserved memory, but does it actually do it?

Answer

No, List doesn't ever decrease the capacity unless you explicitly lower it yourself by setting that property or using TrimExcess, except when you call Clear and it can remove the buffer entirely.

Of course, that's just the current implementation, and it is an implementation detail, so you cannot rely on it not shrinking the backing array.

Comments