0

I am declaring a list like below and then I am adding 12 items to it:

List lstPolygonWkt = new List();

foreach (var i in items) lstPolygonWkt.Add(i.PolygonWkt);

One should think that the list now contains 12 elements, right? But to my surprise it turns out that the list suddenly contains 16 items and then the last 4 items are null. I don't understand why my list which should be 12 items is suddenly 16 items. Any idea why? And how to make the list only 12 items as it should be?

I will paste a couple of screen shots:

enter image description here

enter image description here

Rune Hansen
  • 954
  • 3
  • 16
  • 36
  • Ugh, capacity vs. count. Count = number of items in a collection, Capacity = number of available slots to add more items. A collection is just an array with a wrapper class around it. You drop items in the array until you have reached the Capacity, then the wrapper class has to resize the array. Don't pay any attention to capacity unless you care about memory or performance. No, scratch that, just don't pay any attention to it. I'd suggest you grab a copy of CLR via C#. Its a good read, and will help your conversion to WP7 go smoother. –  Jun 08 '12 at 17:35
  • possible duplicate of [Is it worthwhile to initialize the collection size of a List if it's size reasonably known?](http://stackoverflow.com/questions/2247773/is-it-worthwhile-to-initialize-the-collection-size-of-a-listt-if-its-size-rea) – Hans Passant Jun 08 '12 at 17:46

1 Answers1

8

The list reserves memory in chunks everytime it needs to grow in capacity. Hence capacity reports 16, but count only reports 12. Null items contribute towards the count.

The list class provides the TrimExcess method to remove unutilised space.

Also, specifying the capacity upfront in the constructor results in only one memory grab ( assuming you don't exceed that capacity).

Your screenshot shows a count of 12 with a capacity of 16. If memory serves, the list attempts to double its size (or at the very least definitely defaults to 4, then goes to 8, then 16). As you have 12 items, you triggered the jump from 8 to 16 capacity.

Adam Houldsworth
  • 63,413
  • 11
  • 150
  • 187