Trimexcess on List(Of t) in .net-Collection of common programming errors
Calling TrimExcess
after you load the list will likely save you some memory. But remember that if the items in your list are of a reference type (and strings are reference types), then all you’re saving is the memory required to hold the references.
So, for example, if you have a List(of String)
that’s allocated for 2,000 items and there are only 1,000 items in it, calling TrimExcess
is going to save you the memory occupied by 1,000 references. That’s 4,000 bytes on the 32-bit runtime, and 8,000 bytes on the 64-bit runtime.
As Andrew Hare mentioned, calling TrimExcess
after loading a list that’s going to hang around in memory for a while is probably a good thing. You might also consider calling TrimExcess
if you remove a whole bunch of things from a list, and then you’re going to keep the list around. But calling TrimExcess
repeatedly for the same list, unless it’s really getting large, is just wasting time.