Search code examples
c#liststackqueuecapacity

Why don't Stack<T> and Queue<T> have Capacity property while List<T> does?


Is Capacity property more useful in a List than in the other collections such as Stack and Queue? Or is there another way to get the capacity of a Stack or a Queue?


Solution

  • I think that the reason that List has a Capacity property and Stack and Queue do not is that the normal usage of those types is different.

    For a List it is fairly common to populate it with a large set of values, even some time after it has been created. Providing the Capacity property (and constructor argument) helps to mitigate the number of reallocations that would be done when adding a large number of items to the list.

    Stack and Queue on the other hand do not tend to have large numbers of items added to them at once after they've been created.

    Presumably Microsoft decided that it wasn't worth adding the Capacity property because it wouldn't be used very much.

    However, do note that Queue does have a constructor that allows you to specify an initial capacity, and so does Stack.

    Also note that both classes also have a TrimExcess() method, as mentioned by @drch below.

    So Microsoft thought it would be useful at construction time, but not useful later on - so they only added the capacity functionality to the constructors.

    (Incidentally I've just had a quick check through our code base, and it seems that the only time we use a capacity for List is in fact at construction time. So maybe if Microsoft were designing List now, they might also omit the Capacity property for List...)