Aleksei Maide Aleksei Maide - 10 months ago 57
C# Question

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

When a

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
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?


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.