SYSK 83: On the Importance of Calling TrimToSize

Like StringBuilder (see SYSK 16), ArrayList, Queue and SortedList double the buffer when the existing capacity is exceeded and a new element must be inserted.  Try it for yourself – create an ArrayList and call its Capacity property.  By default, it initializes itself to 16 elements, so you should get 16.  Add 17 items, and call Capacity again.  This time it will be 32 (16 x 2).  When you get to 33 items, the capacity will be 64 (32 x 2), and so on… 

 

So, a good practices is when you’re done initializing a dynamically growing structure like ArrayList, call TrimToSize method, which sets the capacity to the actual number of elements in the ArrayList.  Also, make sure to call TrimToSize before returning the ArrayList data to another class (e.g. if one class holds data in an ArrayList as member variable, and exposes the data via a property).

 

However, you don’t want to over-do it…  Remember, every time the capacity must be increased, we’ll have to allocate a new memory buffer large enough to contain the data, and copy the existing data over…